騰牛網抓取(單頁)

随风小屋發表於2024-08-07

騰牛網抓取(單頁)

建立時間:2024-08-05

一、完整程式碼

import requests
from lxml import etree
url = 'https://www.qqtn.com/wm/meinvtp_1.html'
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0'
}
res = requests.get(url, headers=header)
# data = res.content.decode('gbk') # 手動設定
res.encoding = res.apparent_encoding  # 自動獲取解碼格式
data = res.text
tree = etree.HTML(data)
url_list = tree.xpath('//ul[@class="g-gxlist-imgbox"]//img/@src')
url_title = tree.xpath('//ul[@class="g-gxlist-imgbox"]//a/@title')
for url, title in zip(url_list, url_title):
    print(f'下載{title}中-------')
    with open(f'./tnw/{title}.png', 'wb') as f:
        f.write(requests.get(url).content)

1.1 效果

二、知識點

2.1 xpath解析 中間節點省略

2.2 使用zip遍歷

 zip(*iterables, strict=False)   
 
 
 zip物件產生長度為n的元組,其中n是作為位置引數傳遞給zip()的可迭代物件的數量。每個元組中的第i個元素來自zip()的第i個可迭代引數。這種情況一直持續到最短的論證被用盡為止。如果strict為真,並且其中一個引數先於其他引數用盡,則引發ValueError.

相關文章