写一个可以爬出 图片的python
时间: 2024-06-10 15:06:07 浏览: 11
程序该怎么写?
您可以使用 Python 的 requests 库和 BeautifulSoup 库来实现图片爬虫。具体步骤如下:
1. 首先,使用 requests 库发送 GET 请求获取要爬取的网页的源代码,例如:
```
import requests
url = 'https://www.example.com'
response = requests.get(url)
html = response.content
```
2. 接着,使用 BeautifulSoup 库对返回的 HTML 源码进行解析和筛选。找到所有图片标签并获取它们的 URL:
```
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
img_tags = soup.find_all('img')
urls = [img['src'] for img in img_tags]
```
3. 最后,遍历获取到的图片 URL 并下载图片:
```
import os
for i, url in enumerate(urls):
response = requests.get(url)
filename = os.path.join(os.getcwd(), 'img_{}.jpg'.format(i))
with open(filename, 'wb') as f:
f.write(response.content)
```
注意,在实际爬取时,需要设置 User-Agent 头部信息,处理可能的异常和错误,以及防止不必要的重复请求等问题。