Python爬蟲入門—圖片下載

2.jpg

既然開辟了Python專欄,當然少不了圖片下載了,自己學Python寫的第一個程序就是為了爬圖片的,當時是找了個圖片排列比較規(guī)則的網站糗事百科,然后當?shù)谝粋€程序完工時,看著一張張圖片自己下載到電腦,自己命名打包成文件夾,那個激動啊,然后緊接著又寫了代碼,爬取美女圖,嘿嘿你懂得~后來,就沒怎么用過爬蟲下載圖片了。。。??磥磉€是需求產生動力,屁股決定腦袋!

這次決定寫一個爬蟲程序來爬精美的壁紙圖,壁紙網站看了知乎網友的推薦,選擇的是:

Awesome Wallpapers - wallhaven.cc?alpha.wallhaven.cc

image

此程序支持輸入關鍵詞,根據(jù)查詢結果返回圖片總數(shù)、然后在本地新建文件夾、字典下載圖片到文件夾中。
效果如下:

image

代碼如下:

#_*_ coding:utf-8 _*_
#__author__='陽光流淌007'
#__date__='2018-01-21'
#爬取wallhaven上的的圖片,支持自定義搜索關鍵詞,自動爬取并該關鍵詞下所有圖片并存入本地電腦。
import os
import requests
import time
import random
from lxml import etree

keyWord = input(f"{'Please input the keywords that you want to download :'}")
class Spider():
    #初始化參數(shù)
    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是自定義的,本次程序運行后創(chuàng)建的文件夾路徑,存放各種需要下載的對象。
        self.filePath = ('/users/zhaoluyang/小Python程序集合/桌面壁紙/'+ keyWord + '/')

    def creat_File(self):
        #新建本地的文件夾路徑,用于存儲網頁、圖片等數(shù)據(jù)!
        filePath = self.filePath
        if not os.path.exists(filePath):
            os.makedirs(filePath)

    def get_pageNum(self):
        #用來獲取搜索關鍵詞得到的結果總頁面數(shù),用totalPagenum記錄。由于數(shù)字是夾在形如:1,985 Wallpapers found for “dog”的string中,
        #所以需要用個小函數(shù),提取字符串中的數(shù)字保存到列表numlist中,再逐個拼接成完整數(shù)字。。。
        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是總圖片數(shù),times是總頁面數(shù)
        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):
        #此函數(shù)可以獲取給定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):
        #此函數(shù)用于圖片下載。其中參數(shù)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()

image
image

注意:
圖片雖好,可是下載速度挺慢的,可能和網站服務器有關沒有驗證過網站是否有反爬蟲機制,加了time.sleep(random.uniform(0,2))讓圖片下載完后停頓0-2秒,1來防止給服務器帶來過大壓力,2來也怕被爬蟲機制檢測~

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容