1. 利用requests库爬取https://hellorfimg.zcool.cn/provider_image/large/2238428406.jpg 页面上图片,并保存
时间: 2024-09-12 20:16:57 浏览: 54
好的,首先你需要安装Python的`requests`库和`beautifulsoup4`库,它们分别用于发送HTTP请求和解析HTML内容。如果你还没有安装,可以使用pip命令:
```bash
pip install requests beautifulsoup4
```
然后,你可以按照以下步骤爬取并保存图片:
```python
import requests
from bs4 import BeautifulSoup
# 发送GET请求获取网页内容
url = "https://hellorfimg.zcool.cn/provider_image/large/2238428406.jpg"
response = requests.get(url)
# 检查请求是否成功(状态码200表示成功)
if response.status_code == 200:
# 使用BeautifulSoup解析HTML内容
soup = BeautifulSoup(response.text, 'lxml')
# 找到图片标签(这里假设图片URL在`src`属性中)
img_url = soup.find('img')['src']
# 下载图片
local_filename = 'downloaded_image.jpg'
with open(local_filename, 'wb') as f:
response = requests.get(img_url)
if response.status_code == 200:
f.write(response.content)
print(f"图片已成功下载到本地,文件名为{local_filename}")
else:
print("下载图片失败")
else:
print("请求图片失败,状态码:", response.status_code)
阅读全文