如何用Python的urlretrieve函数实现图片的远程下载示例?

2026-05-16 19:312阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1147个文字,预计阅读时间需要5分钟。

如何用Python的urlretrieve函数实现图片的远程下载示例?

在实现爬虫任务时,除了使用`open()`函数和二进制写入方式下载图片外,还可以考虑以下几种方法:

1. 使用`requests`库: 使用`requests`库可以方便地发送HTTP请求,并直接将响应内容写入文件。 python import requests from PIL import Image from io import BytesIO

def download_image(url, local_path): response=requests.get(url) image=Image.open(BytesIO(response.content)) image.save(local_path)

2. 使用`urllib`库: `urllib`库同样可以用于下载图片,它提供了`urlopen()`函数来获取URL的响应,然后可以像使用`open()`函数一样写入文件。 python from urllib.request import urlopen, urlretrieve from urllib.error import URLError

def download_image(url, local_path): try: response=urlopen(url) with open(local_path, 'wb') as file: file.write(response.read()) except URLError as e: print(e.reason)

3. 使用`BeautifulSoup`库: 如果需要从HTML中提取图片链接,可以使用`BeautifulSoup`库解析HTML,然后获取图片URL并下载。 python from bs4 import BeautifulSoup from urllib.request import urlopen

def download_image(url, local_path): soup=BeautifulSoup(urlopen(url), '.parser') image_url=soup.find('img')['src'] response=urlopen(image_url) with open(local_path, 'wb') as file: file.write(response.read())

4. 使用`aiohttp`库: 对于异步下载图片,可以使用`aiohttp`库,它可以与异步编程一起使用,提高下载效率。 python import aiohttp import asyncio from PIL import Image from io import BytesIO

async def download_image(session, url, local_path): async with session.get(url) as response: image=Image.open(BytesIO(await response.read())) image.save(local_path)

async def main(): url='http://example.com/image.jpg' local_path='local_image.jpg' async with aiohttp.ClientSession() as session: await download_image(session, url, local_path)

asyncio.run(main())

以上方法可以根据具体需求和环境选择合适的方式来实现图片的下载。

在实现爬虫任务时,经常需要将一些图片下载到本地当中。那么在python中除了通过open()函数,以二进制写入方式来下载图片以外,还有什么其他方式吗?本文将使用urlretrieve实现直接远程下载图片。

下面我们再来看看 urllib 模块提供的 urlretrieve() 函数。urlretrieve() 方法直接将远程数据下载到本地。

>>> help(urllib.urlretrieve) Help on function urlretrieve in module urllib: urlretrieve(url, filename=None, reporthook=None, data=None)

参数 finename 指定了保存本地路径(如果参数未指定,urllib会生成一个临时文件保存数据。)

参数 reporthook 是一个回调函数,当连接上服务器、以及相应的数据块传输完毕时会触发该回调,我们可以利用这个回调函数来显示当前的下载进度。

参数 data 指 post 到服务器的数据,该方法返回一个包含两个元素的(filename, headers)元组,filename 表示保存到本地的路径,header 表示服务器的响应头。

下面通过例子来演示一下这个方法的使用,这个例子将 google 的 html 抓取到本地,保存在 D:/google.html 文件中,同时显示下载的进度。

import urllib def cbk(a, b, c): '''回调函数 @a: 已经下载的数据块 @b: 数据块的大小 @c: 远程文件的大小 ''' per = 100.0 * a * b / c if per > 100: per = 100 print '%.2f%%' % per url = 'www.google.com' local = 'd://google.html' urllib.urlretrieve(url, local, cbk)

代码实现

在python中除了使用open()函数实现图片的下载,还可以通过urllib.request模块中的urlretrieve实现直接远程下载图片的操作。以远程下载某网页外设产品图片为例,代码如下:

import requests import urllib.request import os # 系统模块 import shutil # 文件夹控制 def download_pictures(url): headers = { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36"} response = requests.get(url, headers=headers) # 发送网络请求 获取响应 if response.status_code == 200: # 判断请求是否成功 # print(response.json()) # 每次获取数据之前,先将保存图片的文件夹清空 在创建目录 if os.path.exists("img_download"): # 判断文件夹是否存在 shutil.rmtree("img_download") # 存在则删除 os.makedirs("img_download") # 重新创建 else: os.makedirs("img_download") # 不存在 直接创建 content = response.json()["products"] # 获取响应内容 print(content) for index, item in enumerate(content): # 图片地址 img_path = "img13.360buyimg.com/n1/s320x320_" + item["imgPath"] # print(item["imgPath"]) # 根据下标命名图片名称 urllib.request.urlretrieve(img_path, "img_download/" + "img" + str(index) + ".jpg") else: print("请求失败") if __name__ == '__main__': download_pictures("ch.jd.com/hotsale2?cateid=686")

运行结果如下图所示:

如何用Python的urlretrieve函数实现图片的远程下载示例?

到此这篇关于Python使用urlretrieve实现直接远程下载图片的示例代码的文章就介绍到这了,更多相关Python urlretrieve远程下载内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

本文共计1147个文字,预计阅读时间需要5分钟。

如何用Python的urlretrieve函数实现图片的远程下载示例?

在实现爬虫任务时,除了使用`open()`函数和二进制写入方式下载图片外,还可以考虑以下几种方法:

1. 使用`requests`库: 使用`requests`库可以方便地发送HTTP请求,并直接将响应内容写入文件。 python import requests from PIL import Image from io import BytesIO

def download_image(url, local_path): response=requests.get(url) image=Image.open(BytesIO(response.content)) image.save(local_path)

2. 使用`urllib`库: `urllib`库同样可以用于下载图片,它提供了`urlopen()`函数来获取URL的响应,然后可以像使用`open()`函数一样写入文件。 python from urllib.request import urlopen, urlretrieve from urllib.error import URLError

def download_image(url, local_path): try: response=urlopen(url) with open(local_path, 'wb') as file: file.write(response.read()) except URLError as e: print(e.reason)

3. 使用`BeautifulSoup`库: 如果需要从HTML中提取图片链接,可以使用`BeautifulSoup`库解析HTML,然后获取图片URL并下载。 python from bs4 import BeautifulSoup from urllib.request import urlopen

def download_image(url, local_path): soup=BeautifulSoup(urlopen(url), '.parser') image_url=soup.find('img')['src'] response=urlopen(image_url) with open(local_path, 'wb') as file: file.write(response.read())

4. 使用`aiohttp`库: 对于异步下载图片,可以使用`aiohttp`库,它可以与异步编程一起使用,提高下载效率。 python import aiohttp import asyncio from PIL import Image from io import BytesIO

async def download_image(session, url, local_path): async with session.get(url) as response: image=Image.open(BytesIO(await response.read())) image.save(local_path)

async def main(): url='http://example.com/image.jpg' local_path='local_image.jpg' async with aiohttp.ClientSession() as session: await download_image(session, url, local_path)

asyncio.run(main())

以上方法可以根据具体需求和环境选择合适的方式来实现图片的下载。

在实现爬虫任务时,经常需要将一些图片下载到本地当中。那么在python中除了通过open()函数,以二进制写入方式来下载图片以外,还有什么其他方式吗?本文将使用urlretrieve实现直接远程下载图片。

下面我们再来看看 urllib 模块提供的 urlretrieve() 函数。urlretrieve() 方法直接将远程数据下载到本地。

>>> help(urllib.urlretrieve) Help on function urlretrieve in module urllib: urlretrieve(url, filename=None, reporthook=None, data=None)

参数 finename 指定了保存本地路径(如果参数未指定,urllib会生成一个临时文件保存数据。)

参数 reporthook 是一个回调函数,当连接上服务器、以及相应的数据块传输完毕时会触发该回调,我们可以利用这个回调函数来显示当前的下载进度。

参数 data 指 post 到服务器的数据,该方法返回一个包含两个元素的(filename, headers)元组,filename 表示保存到本地的路径,header 表示服务器的响应头。

下面通过例子来演示一下这个方法的使用,这个例子将 google 的 html 抓取到本地,保存在 D:/google.html 文件中,同时显示下载的进度。

import urllib def cbk(a, b, c): '''回调函数 @a: 已经下载的数据块 @b: 数据块的大小 @c: 远程文件的大小 ''' per = 100.0 * a * b / c if per > 100: per = 100 print '%.2f%%' % per url = 'www.google.com' local = 'd://google.html' urllib.urlretrieve(url, local, cbk)

代码实现

在python中除了使用open()函数实现图片的下载,还可以通过urllib.request模块中的urlretrieve实现直接远程下载图片的操作。以远程下载某网页外设产品图片为例,代码如下:

import requests import urllib.request import os # 系统模块 import shutil # 文件夹控制 def download_pictures(url): headers = { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36"} response = requests.get(url, headers=headers) # 发送网络请求 获取响应 if response.status_code == 200: # 判断请求是否成功 # print(response.json()) # 每次获取数据之前,先将保存图片的文件夹清空 在创建目录 if os.path.exists("img_download"): # 判断文件夹是否存在 shutil.rmtree("img_download") # 存在则删除 os.makedirs("img_download") # 重新创建 else: os.makedirs("img_download") # 不存在 直接创建 content = response.json()["products"] # 获取响应内容 print(content) for index, item in enumerate(content): # 图片地址 img_path = "img13.360buyimg.com/n1/s320x320_" + item["imgPath"] # print(item["imgPath"]) # 根据下标命名图片名称 urllib.request.urlretrieve(img_path, "img_download/" + "img" + str(index) + ".jpg") else: print("请求失败") if __name__ == '__main__': download_pictures("ch.jd.com/hotsale2?cateid=686")

运行结果如下图所示:

如何用Python的urlretrieve函数实现图片的远程下载示例?

到此这篇关于Python使用urlretrieve实现直接远程下载图片的示例代码的文章就介绍到这了,更多相关Python urlretrieve远程下载内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!