用python从网页上爬取图片
时间: 2024-05-26 21:04:48 浏览: 64
通过python爬取网页图片
5星 · 资源好评率100%
可以使用Python中的Requests和BeautifulSoup库来实现从网页上爬取图片的功能。具体步骤如下:
1. 导入所需库:
```python
import requests
from bs4 import BeautifulSoup
import os
```
2. 发送请求并解析网页:
```python
url = "http://www.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
```
3. 找到所有的图片链接:
```python
img_urls = []
for img in soup.find_all('img'):
img_urls.append(img.get('src'))
```
4. 下载图片到本地:
```python
for url in img_urls:
response = requests.get(url)
img_name = os.path.basename(url)
with open(img_name, 'wb') as f:
f.write(response.content)
```
完整代码示例:
```python
import requests
from bs4 import BeautifulSoup
import os
url = "http://www.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
img_urls = []
for img in soup.find_all('img'):
img_urls.append(img.get('src'))
for url in img_urls:
response = requests.get(url)
img_name = os.path.basename(url)
with open(img_name, 'wb') as f:
f.write(response.content)
```
注意:在实际应用中,需要根据具体情况进行适当的错误处理和异常处理。
阅读全文