分别用urlib库和requests库下载上述网址图片
时间: 2024-06-05 20:06:21 浏览: 13
使用urllib库下载图片:
```python
import urllib.request
url = 'https://www.example.com/img/picture.jpg'
urllib.request.urlretrieve(url, 'picture.jpg')
```
使用requests库下载图片:
```python
import requests
url = 'https://www.example.com/img/picture.jpg'
response = requests.get(url)
with open('picture.jpg', 'wb') as f:
f.write(response.content)
```
相关问题
用requests或者bs4第三方库批量下载百度图片
首先需要确定要下载的图片的关键字和数量,然后可以通过百度图片的搜索API获取图片的URL,再使用requests库下载图片,最后保存到本地。
以下是一个示例代码:
```python
import requests
from bs4 import BeautifulSoup
import os
keyword = "猫" # 搜索关键字
num_images = 10 # 要下载的图片数量
url = f"https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord={keyword}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&word={keyword}&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=&fr=&expermode=&force=&pn=0&rn={num_images}"
response = requests.get(url)
content = response.content.decode('utf-8')
soup = BeautifulSoup(content, 'html.parser')
img_tags = soup.find_all('img', class_='main_img')
if not os.path.exists(keyword):
os.makedirs(keyword)
for i, img_tag in enumerate(img_tags):
img_url = img_tag.get('src')
response = requests.get(img_url)
with open(f"{keyword}/{i}.jpg", "wb") as f:
f.write(response.content)
```
这个示例代码会在当前目录下创建一个以关键字命名的文件夹,并下载指定数量的图片到该文件夹中。注意,这个示例代码没有进行错误处理和异常处理,实际使用时需要根据需要进行处理。
使用requests库爬取图片
以下是一个简单的示例,使用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请求来获取图片数据。接下来,我们将图片数据写入一个文件中,以便保存到本地文件系统中。最后,我们打印一条消息来确认图片已成功下载。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)