python中selenium爬取图片
时间: 2023-10-29 10:57:00 浏览: 84
使用selenium爬取图片可以分为以下步骤:
1. 安装selenium和webdriver
```python
pip install selenium
```
下载对应浏览器的webdriver,例如Chrome的webdriver下载地址为:http://chromedriver.chromium.org/downloads
2. 加载网页
```python
from selenium import webdriver
browser = webdriver.Chrome() # 初始化浏览器
browser.get(url) # 打开网页
```
3. 定位图片元素并获取图片链接
```python
img_element = browser.find_element_by_xpath('xpath_of_the_image_element')
img_url = img_element.get_attribute('src')
```
4. 下载图片
```python
import requests
response = requests.get(img_url, stream=True)
with open('image.jpg', 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
```
完整代码如下:
```python
from selenium import webdriver
import requests
url = 'https://www.example.com'
browser = webdriver.Chrome()
browser.get(url)
img_element = browser.find_element_by_xpath('xpath_of_the_image_element')
img_url = img_element.get_attribute('src')
response = requests.get(img_url, stream=True)
with open('image.jpg', 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
browser.quit()
```
阅读全文