使用requests库爬取图片
时间: 2024-06-04 15:13:48 浏览: 82
以下是一个简单的示例,使用requests库从网站上下载图片:
```python
import requests
# URL of the image to be downloaded
url = "https://www.example.com/image.jpg"
# Send a GET request to the URL
response = requests.get(url)
# Open a file to write the image data to
with open("image.jpg", "wb") as f:
f.write(response.content)
print("Image downloaded!")
```
在上面的代码中,我们首先指定要下载的图片的URL,然后使用requests库发送一个GET请求来获取图片数据。接下来,我们将图片数据写入一个文件中,以便保存到本地文件系统中。最后,我们打印一条消息来确认图片已成功下载。
相关问题
requests库爬取图片
### 使用Python Requests库进行图片爬取
为了利用`requests`库来抓取网页上的图片,需遵循一系列操作流程以确保过程顺利。
安装`requests`库可以通过pip工具完成,在Windows环境下通过命令提示符执行`pip install requests`;对于Linux系统,则采用`sudo pip install requests`命令[^3]。一旦环境配置完毕,便能着手编写用于下载图片的脚本。
创建一个新的Python文件并导入必要的模块:
```python
import os
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup # 如果需要解析HTML文档的话
```
定义目标URL地址以及本地存储路径:
```python
base_url = "http://example.com/" # 替换成实际的目标站点URL
save_dir = "./images/"
if not os.path.exists(save_dir):
os.makedirs(save_dir)
```
发起HTTP GET请求获取页面内容,并从中提取所有图像链接:
```python
response = requests.get(base_url)
soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')
urls = [img['src'] for img in img_tags]
full_urls = []
for u in urls:
full_u = urljoin(base_url, u) # 将相对路径转换成绝对路径
full_urls.append(full_u)
```
遍历这些链接逐个下载对应的图片资源到指定目录下:
```python
for i, url in enumerate(full_urls):
try:
response_img = requests.get(url)
file_name = save_dir + str(i+1)+".jpg"
with open(file_name, 'wb') as f:
f.write(response_img.content)
print(f"{file_name} saved.")
except Exception as e:
print(e)
```
上述代码片段展示了完整的从Web服务器拉取图片的过程[^4]。值得注意的是,在真实场景应用此技术前应当了解目标网站的服务条款,尊重版权与隐私政策规定。
用bs4和requests库爬取优美图库
以下是使用Python的requests和BeautifulSoup库爬取优美图库的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.umei.cc/meinvtupian/'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
for img in soup.find_all('img'):
print(img.get('src'))
```
首先,我们定义了要爬取的网址,并使用requests库向该网址发送GET请求。然后,我们将响应内容传递给BeautifulSoup对象进行解析。
在这个例子中,我们使用了soup.find_all('img')来找到网页中所有的图片标签,然后使用img.get('src')获取每个图片标签中的src属性值(即图片链接)。
最后,我们可以将这些链接打印出来,或使用其他方法进行进一步处理。
阅读全文
相关推荐













