python如何爬取xpath图片
时间: 2023-07-07 10:36:48 浏览: 99
要爬取xpath图片,你需要使用Python中的requests库和lxml库,具体步骤如下:
1. 发送HTTP请求获取HTML页面源代码
```python
import requests
url = 'http://example.com'
response = requests.get(url)
html = response.content.decode('utf-8')
```
2. 使用lxml库解析HTML页面
```python
from lxml import etree
selector = etree.HTML(html)
```
3. 使用xpath表达式定位图片元素
```python
img_elements = selector.xpath('//img')
```
4. 遍历图片元素,获取图片链接并下载图片
```python
import os
save_dir = 'images'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
for img_element in img_elements:
img_url = img_element.xpath('@src')[0]
img_name = img_url.split('/')[-1]
img_path = os.path.join(save_dir, img_name)
img_data = requests.get(img_url).content
with open(img_path, 'wb') as f:
f.write(img_data)
```
这样就可以爬取xpath图片了。
阅读全文