如何使用python爬取网页图片
时间: 2023-09-20 20:12:56 浏览: 97
您可以使用Python中的第三方库requests和beautifulsoup4来爬取网页图片。具体步骤如下:
1.导入requests和beautifulsoup4库
```python
import requests
from bs4 import BeautifulSoup
```
2.设置请求头信息
```python
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
```
3.发送请求获取网页内容
```python
url = 'http://www.example.com'
response = requests.get(url, headers=headers)
```
4.解析网页内容获取图片链接
```python
soup = BeautifulSoup(response.content, 'html.parser')
img_tags = soup.find_all('img')
urls = [img['src'] for img in img_tags]
```
5.下载图片
```python
for url in urls:
response = requests.get(url, headers=headers)
with open('image_name.jpg', 'wb') as f:
f.write(response.content)
```
其中,'image_name'为你想要保存的图片名字。
阅读全文