python爬虫爬取图片
时间: 2023-11-08 15:47:47 浏览: 40
可以使用 Python 的 Requests 库和 Beautiful Soup 库来爬取图片。
首先,使用 Requests 库发送 HTTP 请求获取页面的 HTML 代码,然后使用 Beautiful Soup 库解析 HTML 代码,找到图片的 URL。最后,使用 Requests 库下载图片。
以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 发送 HTTP 请求,获取页面 HTML 代码
url = 'https://www.example.com'
response = requests.get(url)
html = response.text
# 使用 Beautiful Soup 解析 HTML 代码,找到图片 URL
soup = BeautifulSoup(html, 'html.parser')
img_tags = soup.find_all('img')
img_urls = [img['src'] for img in img_tags]
# 使用 Requests 下载图片
for img_url in img_urls:
img_response = requests.get(img_url)
with open('image.jpg', 'wb') as f:
f.write(img_response.content)
```
注意,上述代码只会下载第一张图片。如果要下载所有图片,需要在循环中调用不同的文件名。另外,还需要处理一些异常情况,例如找不到图片 URL 或下载失败等。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)