# -*- coding: utf-8 -*- import requests, time, os from lxml import etree from urllib import request name_url = {} # 創建一個字典 def sort(): req = requests.get('https://www.tujigu.com/') # 首頁 req.encoding = 'utf-8' # 中文出現亂碼,調整編碼 req_xp = etree.HTML(req.text) # 裝換為xp,text是為了變成字符串形式,不然會報錯 text_list = req_xp.xpath('//*[@class="menu"]/li/a/text()|//*[@id="tag_ul"]/li/a/text()') # 讀取分類名 href_list = req_xp.xpath('//*[@class="menu"]/li/a/@href|//*[@id="tag_ul"]/li/a/@href') # 獲取網址 for href, text in zip(href_list, text_list): name_url[text] = href # 已分類名做為key,網址作為值 return text_list # 返回分類名列表,好為后面打印分類名 def dow(url, name): if not os.path.exists("圖集谷"): # 檢查並創建文件夾,強迫症~~~ os.mkdir('圖集谷') if not os.path.exists("圖集谷/{}".format(name)): # 同上,創建分類 os.mkdir('圖集谷/{}'.format(name)) atlas = requests.get(url) # get你選擇的網址 atlas.encoding = 'utf-8' # 同上,亂碼問題 atlas_xp = etree.HTML(atlas.text) text_list = atlas_xp.xpath('//*[@class="biaoti"]/a/text()') # 獲取圖集名 href_list = atlas_xp.xpath('//*[@class="biaoti"]/a/@href') for text, href in zip(text_list, href_list): req = requests.get(href) req.encoding = 'utf-8' req_xp1 = etree.HTML(req.text) src_list = req_xp1.xpath('//*[@class="content"]/img/@src') num = 1 # 創建圖片名,美觀 # 下面是為了刪除一些圖集中包含了文件夾不能創建的符號 text = text.replace('\n', '').replace('/', '').replace('\\', '').replace(':', '').replace('*', '').replace('"', '').replace( '<', '').replace('>', '').replace('|', '').replace('?', '') if not os.path.exists("圖集谷/{}/{}".format(name, text)): # 檢測此圖集是否下載過 os.mkdir("圖集谷/{}/{}".format(name, text)) for src in src_list: request.urlretrieve(src, "圖集谷/{}/{}/{}.jpg".format(name, text, num)) # 保存圖片 num += 1 print('{}-------------成功下載'.format(text)) else: print('{}--------------內容已下載'.format(text)) def get(): while 1: text_list = sort() # 從首頁獲取分類信息和url i = 1 # 序號 for text in text_list[2:-1]: # 從2到-1是為了去除沒用的分類 print('%02d.{}'.format(text) % i) # 打印分類信息 i += 1 opt = input('輸入您要爬取的內容(首頁為默認)>>>>> ') if not opt.isdigit(): # 判斷輸入內容 print('傻X輸入中文懂么') time.sleep(3) continue opt = int(opt) if not 0 < opt < len(text_list) - 3: # 判斷輸入內容 print('輸入范圍錯誤') time.sleep(3) continue opt += 1 # 以為刪除了首頁,所以+1才能正確選擇分類 url = name_url[text_list[opt]] # 獲取你選擇的地址 name = text_list[opt] # 分類的名字,好創建一個文件夾放入 print('{}====開始爬取'.format(name)) dow(url, name) # 開始運行下載程序 input('爬取完成,按下回車重新開始') if __name__ == '__main__': get() # 開始運行主程序
安裝好庫,選擇自己喜好,就可以了。