- 获得图片链接,网上的图片都有唯一的url
import urllib.request image_url=‘https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1569075968903&di=6e275342eb912831affe1c2f5511e05d&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F14c272157c7345f33bab613327d7ee11a8b2c5344ea1a-rSck09_fw658‘ # 方法一: urllib.request.urlretrieve(image_url,‘chun.jpg‘) # 方法二: response=urllib.request.urlopen(image_url) file=open(r‘E:\qing.jpg‘,‘wb‘)# 二进制格式,wb二进制格式写入 file.write(response.read()) file.close()#方法三: with open(‘qing.jpg‘,‘wb‘) as fp: fp.write(response.read())
- 熟悉urllib的各类函数的使用
import urllib.request url=‘http://www.baidu.com‘ response=urllib.request.urlopen(url=url) print(response.readlines()) print(dict(response.getheaders())) print(response.read().decode()) with open(‘baidu.html‘,‘w‘,encoding=‘utf8‘)as fp: fp.write(response.read().decode())
- 图片获取步骤:
- 得到url
- response=urllib.request.urlopen(url)打开获得的url
- response.read().decode()# decode()将读出的信息以二进制字节形式打开,
- 将获得的文件输出,有方法一,方法二、方法三可以直接进行传数
- 方法一:
with open(r‘E:\qing.jpg‘,‘wb‘) as fp:# wb以二进制字节进行读写 fp.write(response.read())
- 方法二:
file=open(r‘E:\qing.jpg‘,‘wb‘) file.write(url) file.close()
原文地址:https://www.cnblogs.com/ybl20000418/p/11564425.html
时间: 2024-10-31 16:42:14