python

python xpath爬虫能抓取图片吗

小樊
100
2024-12-11 02:07:07
栏目: 编程语言

Python的XPath爬虫主要用于抓取网页上的文本内容,而不是图片。但是,你可以通过以下方法获取图片URL并使用其他库(如requests)下载图片:

  1. 使用XPath提取图片的URL:
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')
  1. 使用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。

0
看了该问题的人还看了