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。