既然開闢了Python專欄,當然少不了圖片下載了,自己學Python寫的第一個程序就是為了爬圖片的,當時是找了個圖片排列比較規則的網站糗事百科,然後當第一個程序完工時,看著一張張圖片自己下載到電腦,自己命名打包成文件夾,那個激動啊,然後緊接著又寫了代碼,爬取美女圖,嘿嘿你懂得~後來,就沒怎麼用過爬蟲下載圖片了。。。。看來還是需求產生動力,屁股決定腦袋!
這次決定寫一個爬蟲程序來爬精美的壁紙圖,壁紙網站看了知乎網友的推薦,選擇的是:
Awesome Wallpapers - https://wallhaven.cc/
此程序支持輸入關鍵詞,根據查詢結果返回圖片總數、然後在本地新建文件夾、字典下載圖片到文件夾中。
效果如下:
代碼如下:
<code>#_*_ coding:utf-8 _*_#__author__='Lyon'#__date__='2018-01-21'#爬取wallhaven上的的圖片,支持自定義搜索關鍵詞,自動爬取並該關鍵詞下所有圖片並存入本地電腦。import osimport requestsimport timeimport randomfrom lxml import etreekeyWord = input(f"{'Please input the keywords that you want to download :'}")class Spider(): #初始化參數 def __init__(self): #headers是請求頭,"User-Agent"、"Accept"等字段都是通過谷歌Chrome瀏覽器查找的! self.headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36", } #filePath是自定義的,本次程序運行後創建的文件夾路徑,存放各種需要下載的對象。 self.filePath = ('/users/zhaoluyang/小Python程序集合/桌面壁紙/'+ keyWord + '/') def creat_File(self): #新建本地的文件夾路徑,用於存儲網頁、圖片等數據! filePath = self.filePath if not os.path.exists(filePath): os.makedirs(filePath) def get_pageNum(self): #用來獲取搜索關鍵詞得到的結果總頁面數,用totalPagenum記錄。由於數字是夾在形如:1,985 Wallpapers found for “dog”的string中, #所以需要用個小函數,提取字符串中的數字保存到列表numlist中,再逐個拼接成完整數字。。。 total = "" url = ("https://alpha.wallhaven.cc/search?q={}&categories=111&purity=100&sorting=relevance&order=desc").format(keyWord) html = requests.get(url) selector = etree.HTML(html.text) pageInfo = selector.xpath('//header[@class="listing-header"]/h1[1]/text()') string = str(pageInfo[0]) numlist = list(filter(str.isdigit,string)) for item in numlist: total += item totalPagenum = int(total) return totalPagenum def main_fuction(self): #count是總圖片數,times是總頁面數 self.creat_File() count = self.get_pageNum() print("We have found:{} images!".format(count)) times = int(count/24 + 1) j = 1 for i in range(times): pic_Urls = self.getLinks(i+1) for item in pic_Urls: self.download(item,j) j += 1 def getLinks(self,number): #此函數可以獲取給定numvber的頁面中所有圖片的鏈接,用List形式返回 url = ("https://alpha.wallhaven.cc/search?q={}&categories=111&purity=100&sorting=relevance&order=desc&page={}").format(keyWord,number) try: html = requests.get(url) selector = etree.HTML(html.text) pic_Linklist = selector.xpath('//a[@class="jsAnchor thumb-tags-toggle tagged"]/@href') except Exception as e: print(repr(e)) return pic_Linklist def download(self,url,count): #此函數用於圖片下載。其中參數url是形如:https://alpha.wallhaven.cc/wallpaper/616442/thumbTags的網址 #616442是圖片編號,我們需要用strip()得到此編號,然後構造html,html是圖片的最終直接下載網址。 string = url.strip('/thumbTags').strip('https://alpha.wallhaven.cc/wallpaper/') html = 'http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-' + string + '.jpg' pic_path = (self.filePath + keyWord + str(count) + '.jpg' ) try: pic = requests.get(html,headers = self.headers) f = open(pic_path,'wb') f.write(pic.content) f.close() print("Image:{} has been downloaded!".format(count)) time.sleep(random.uniform(0,2)) except Exception as e: print(repr(e))spider = Spider()spider.main_fuction()/<code>
注意:
圖片雖好,可是下載速度挺慢的,可能和網站服務器有關~沒有驗證過網站是否有反爬蟲機制,加了time.sleep(random.uniform(0,2))讓圖片下載完後停頓0~2秒,1來防止給服務器帶來過大壓力,2來也怕被爬蟲機制檢測~
閱讀更多 Flowingbit 的文章