Python - 爬取圖片並下載到本地

import requests             #用來模擬瀏覽器發送網絡請求
from lxml import etree      #解析數據
from urllib import request  #下載保存urlretrive()
import time                 #time.sleep讓程序延遲幾秒再進行

# 函數的封裝 def
def huya_spider():
    # 請求數據:
    url = 'https://www.huya.com/g/2168#tag2609'
    User_Agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36"
    headers = {
        'User_Agent':User_Agent
    }
    res = requests.get(url)
    result = res.text
    print(res)


    data = etree.HTML(result)
    alist = data.xpath('//img[@class="pic"]')

    cnt = 0

    for woman in alist:
        cnt = cnt + 1
        # 通過已經篩選的數據進行獲取對應的圖片
        img = woman.xpath('./@data-original')[0]
        img = img.split("?")[0]

        #進行保存數據
        name = woman.xpath('./@alt')[0]

        path = 'D:\\img\\'

        #下載保存
        #異常處理
        try:
            print(img)
            path2 = path + str(cnt) + ".png"
            print(path2)
            request.urlretrieve(img, path2)
        except Exception as e:
            print(e)
            pass

        #顯示打印進度
        # print("<%s> 下載完畢!" % name)

        time.sleep(3)


huya_spider()

# print("Hello World!")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章