1. 程式人生 > 實用技巧 >python例項:爬取caoliu圖片,同時下載到指定的資料夾內

python例項:爬取caoliu圖片,同時下載到指定的資料夾內

本指令碼主要實現爬取caoliu某圖片板塊,前3頁當天更新的帖子的所有圖片,同時把圖片下載到對應帖子名建立的資料夾中

爬蟲主要通過python xpath來實現,同時指令碼內包含,建立資料夾,分割資料,下載等操作

首先,我們分析下caoliu某圖片板塊的資源連結

貼子對應的頁面元素

展開元素,可以看到帖子的實際地址,所以我們第一步就是把地址都給扒下來

AA裡包含了caoliu某圖片板塊前3頁的地址,建立lit空集來收集爬取來的帖子地址

def stepa (AA):
    lit=[]
    for url in AA:
        response = requests.get(url=url, headers=headers, timeout=100000)
        wb_data 
= response.text.encode('iso-8859-1').decode('gbk')#caoliu的編碼格式需要對返回值重新轉碼 # 將頁面轉換成文件樹 html = etree.HTML(wb_data) a = html.xpath('//td[@class="tal"]//@href')#帖子地址xpath lit.append(a) return(lit) alllink = stepa(AA) alllink=alllink[0]

執行後的結果

我們獲得帖子地址後,獲取的帖子地址如上圖,所以需要對地址進行處理,同時遮蔽掉站務貼

BB是需要遮蔽掉的站務貼集合,alllink是上一步驟獲取的圖貼集合,建立迴圈,從alllink集合裡每次取一個連結,if用於跳過賬務貼

def stepb(alllink,headers,BB):
    for url in alllink:
        #print(url)
        if "read"  in url:
            continue
        elif url in BB:
            continue
        else:
            url='https://cl.hexie.xyz/'+url
            
print(url) response = requests.get(url, headers=headers) response=response.text.encode('iso-8859-1').decode('gbk') html = etree.HTML(response) b = html.xpath('//div[@class="tpc_content do_not_catch"]//@ess-data')#圖片地址xpath title = html.xpath('/html/head/title/text()')#帖子名稱xpath title=title[0] title=title[:-27]#去掉帖子名稱後面共同的和影響建立資料夾的部分 print(title)

因為獲取的連結”htm_data/2011/8/4182612.html“需要重新拼接

拼接步驟”url='https://cl.hexie.xyz/'+url“

後面的步驟就是訪問拼接好的url,獲取帖子內的圖片地址,我們分析下圖片資源的元素資訊

圖片地址存放在"tpc_content do_not_catch"class內,所以xpath可寫成”

//div[@class="tpc_content do_not_catch"]//@ess-data“

如此,圖片地址就獲取到了

接下來,就是通過地址,下載圖片資源到本地

建立資料夾參考:https://www.cnblogs.com/becks/p/13977943.html

下載圖片到本地參考:https://www.cnblogs.com/becks/p/13978612.html

附上整個指令碼

# -*-coding:utf8-*-
# encoding:utf-8
# 本指令碼用於爬取草榴圖片板塊(新時代的我們)最近3天的所有帖子的所有圖片,每一個帖子建立獨立的資料夾,圖片下載到資料夾中
import requests
from lxml import etree
import os
import sys
import re
import random
from urllib import request
import io

#sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')
#解決vscode視窗輸出亂碼的問題,需要import io 和import sys

headers = {
    'authority': 'cl.hexie.xyz',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'sec-fetch-site': 'none',
    'sec-fetch-mode': 'navigate',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cookie': '__cfduid=d9b8dda581516351a1d9d388362ac222c1603542964',
}    

path = os.path.abspath(os.path.dirname(sys.argv[0]))

AA=[
    "https://cl.和諧.xyz/thread0806.php?fid=8",
   #"https://cl.和諧.xyz/thread0806.php?fid=8&search=&page=2",
   #"https://cl.和諧.xyz/thread0806.php?fid=8&search=&page=3"
    ]

#AA裡包含最新前3頁列表連結

BB=["htm_data/1109/8/594739.html",
    "htm_data/1803/8/3018643.html",
    "htm_data/0706/8/36794.html",
    "htm_data/1106/8/524775.html",
    "htm_data/2011/8/344500.html"]

#BB裡面包含需要跳過的帖子,這部分帖子是站務貼,裡面沒資源

#第1步,獲取每一頁所有的帖子地址,地址格式“https://cl.和諧.xyz/htm_data/2011/8/4182841.html”
def stepa (AA):
    lit=[]
    for url in AA:
        response = requests.get(url=url, headers=headers, timeout=100000)
        wb_data = response.text.encode('iso-8859-1').decode('gbk')#草榴的編碼格式需要對返回值重新轉碼
        # 將頁面轉換成文件樹
        html = etree.HTML(wb_data)
        a = html.xpath('//td[@class="tal"]//@href')#帖子地址xpath
        lit.append(a)
    return(lit) 
alllink = stepa(AA)
alllink=alllink[0]

#第2步,獲取每一篇帖子裡所有圖片的地址,地址格式“https://和諧.xyz/i/2020/11/15/sedlrk.jpg"
def stepb(alllink,headers,BB):
    for url in alllink:
        #print(url)
        if "read"  in url:
            continue
        elif url in BB:
            continue
        else:
            url='https://cl.和諧.xyz/'+url
            print(url)
            response = requests.get(url, headers=headers)
            response=response.text.encode('iso-8859-1').decode('gbk')
            html = etree.HTML(response)
            b = html.xpath('//div[@class="tpc_content do_not_catch"]//@ess-data')#圖片地址xpath
            title = html.xpath('/html/head/title/text()')#帖子名稱xpath
            title=title[0]
            title=title[:-27]#去掉帖子名稱後面共同的和影響建立資料夾的部分
            print(title)

            path2 = r'D://tu' 
            os.mkdir(path2 + './'+str(title))
            #以上兩行即在d盤tu目錄下建立名稱為變數title的資料夾

            for c in b:
                print("loading"+" " +c)
                pic_name = random.randint(0,100)#圖片名稱隨機命令

                r = requests.get(c,stream=True,headers=headers)
                time = r.elapsed.total_seconds()#獲取響應時間
                if time > 1000:
                    continue
                else:
                    with open(path2 + './'+str(title) +'./'+str(pic_name) +'.jpg', 'wb') as fd:
                        for chunk in r.iter_content():
                            fd.write(chunk)
                #從87行開始即下載的指令碼,把圖片下載到上文建立的指定資料夾中

stepb(alllink,headers,BB)

#第3步:提示爬取完成
def over():
    print("ok")
over()   

嘿嘿