selenium 爬取图片
时间: 2023-09-01 14:10:12 浏览: 119
使用Selenium可以实现爬取图片的功能。首先,需要准备好Chrome浏览器的驱动,并将其路径配置到代码中。然后,通过Selenium打开目标网页,并使用XPath定位到图片元素。接下来,使用requests库发送请求,将图片保存到本地的指定路径。最后,关闭浏览器。以下是整体代码的步骤:
步骤1: 驱动浏览器
```python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
wd = webdriver.Chrome(service=Service(r'chromedriver.exe'))
```
步骤2: 打开目标网页并定位图片元素
```python
wd.get("https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&dyTabStr=MCwzLDYsMSw1LDQsOCw3LDIsOQ==&word=海绵宝宝")
wd.implicitly_wait(5)
elements = wd.find_elements(By.XPATH, "//*[@class='main_img img-hover']")
```
步骤3: 保存图片到指定路径
```python
import requests
import os
import time
d = "D:\study material\海绵宝宝图"
i = 0
time.sleep(2)
for element in elements:
i += 1
print('----------------')
t = element.get_attribute('src')
print(t)
path = "D:\study material\海绵宝宝图\图{}.jpg".format(i)
r = requests.get(t)
r.raise_for_status()
with open(path, 'wb') as f:
f.write(r.content)
f.close()
print('保存成功')
```
步骤4: 关闭浏览器
```python
wd.quit()
```
以上是使用Selenium实现爬取图片的代码。你可以根据自己的需求调整代码中的路径和其他参数。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [python基于Selenium方法爬取网页图片](https://blog.csdn.net/Chengxuyuan0307/article/details/129363743)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文