我们想用requests从网络上下载图片,可以这样操作
- 打开Google浏览器,先搜索到图片,如下我们先搜索“赛亚人悟空”,找到我们想下载的图片
- 点开Google浏览器的检查
在html页面上可以获得到src的网址https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn10110%2F492%2Fw1080h1812%2F20190412%2Fcda4-hvntnkq9542192.jpg&refer=http%3A%2F%2Fn.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633157078&t=0220592068184dc312ca1a187f575bc6
- 然后我们就可以用requests.get()方法去下载了,代码如下:
url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn10110%2F492%2Fw1080h1812%2F20190412%2Fcda4-hvntnkq9542192.jpg&refer=http%3A%2F%2Fn.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633157078&t=0220592068184dc312ca1a187f575bc6"
response = requests.get(url, stream=True)
try:
with open('/Users/Felix/Desktop/saya.png', 'wb') as logFile:
for chunk in response:
logFile.write(chunk)
logFile.close()
print("Download done!")
except Exception as e:
print("Download log error!")
- 检查写入文件的路径,已存在此文件
当然,如果想批量下载文件,可以先找到url的规律,像很多网站上的图片,同一个页面的图片source url都是按照序列号排列的,找到规律后将以上方法封装起来使用即可