天天看點

Python爬蟲練習-Xpath解析圖檔爬取

import os
import requests
from lxml import etree

if __name__ == '__main__':
    # UA僞裝
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.70 Safari/537.36'
    }
    # 指定url
    url = 'https://pic.netbian.com/4kmeinv/'
    # 發起請求
    response = requests.get(url=url, headers=headers)
    # 手動設定響應資料的編碼格式
    # response.encoding = 'utf-8'
    page_text = response.text
    # xpath解析标簽
    tree = etree.HTML(page_text)
    div_list = tree.xpath('//div[@class="slist"]//li')
    # 判斷檔案夾
    if not os.path.exists('./img'):
        os.mkdir('./img')
    for div in div_list:
        # 解析擷取圖檔位址
        img_src = 'https://pic.netbian.com/' + div.xpath('./a/img/@src')[0]
        img_alt = div.xpath('./a/b/text()')[0] + '.jpg'
        # 通用進行中文亂碼的解決方案
        img_alt = img_alt.encode('iso-8859-1').decode('gbk')
        # print(img_alt, img_src)
        # 發起請求
        page_img = requests.get(url=img_src, headers=headers).content
        # 圖檔路徑
        img_path = 'img/' + img_alt
        # 儲存
        with open(img_path, 'wb') as fp:
            fp.write(page_img)
            print(img_alt, "--下載下傳成功--")
           

ps:注意中文亂碼情況