Python的XPath爬蟲主要用于抓取網頁上的文本內容,而不是圖片。但是,你可以通過以下方法獲取圖片URL并使用其他庫(如requests
)下載圖片:
from lxml import html
import requests
url = 'https://example.com'
response = requests.get(url)
tree = html.fromstring(response.content)
image_urls = tree.xpath('//img/@src')
requests
庫下載圖片:for image_url in image_urls:
response = requests.get(image_url, stream=True)
with open('image.jpg', 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
這樣,你就可以使用Python爬蟲抓取并下載圖片了。請注意,這僅適用于公開可訪問的圖片。如果你需要抓取受保護的圖片,可能需要考慮使用其他方法,如模擬登錄或使用API。