用beautifulsoup爬取网页图片
时间: 2023-04-19 14:00:58 浏览: 142
【python爬虫】Python图片爬虫爬取Lofter图片.zip
使用BeautifulSoup可以轻松地爬取网页图片。以下是一些基本步骤:
1. 导入必要的库
```python
from bs4 import BeautifulSoup
import requests
```
2. 获取网页内容
```python
url = 'https://www.example.com'
response = requests.get(url)
html = response.text
```
3. 解析HTML内容
```python
soup = BeautifulSoup(html, 'html.parser')
```
4. 找到图片标签
```python
img_tags = soup.find_all('img')
```
5. 提取图片链接
```python
img_urls = [img['src'] for img in img_tags]
```
6. 下载图片
```python
for url in img_urls:
response = requests.get(url)
with open('image.jpg', 'wb') as f:
f.write(response.content)
```
以上是一个简单的例子,可以根据实际情况进行修改和优化。
阅读全文