Python3通过request.urlopen实现Web网页图片下载

  • 先贴代码(设置请求头信息,模拟浏览器。绕过反爬虫拦截):
import requests, json, time, sys
from urllib import request
from contextlib import closing
url = 'http://oa.xxxx.com/Images/bd86105c-6410-479e-9fcf-47bb78d457bb.jpg'
req = request.Request(url, headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
            'Cookie':'SESSION=765bff9a-d6ff-4538-93ae-1a1fa2e3c327; _ga=GA1.2.833023310.1552467160; UM_distinctid=16adf48e17275d-0be8cf00f7c334-353166-1fa400-16adf48e173580; ASP.NET_SessionId=oitt4mutnu0kou1usezqdbf4'

        })
res = request.urlopen(req)
# print(res.read())
with res as response, open("3.png",'wb') as f_save:
            f_save.write(response.read())
            f_save.flush()
            f_save.close()
  • 通过 request.urlretrieve() 实现图片下载,只要两行代码。但是缺点是:如果要下载网站设置了反爬虫,就会失败!
from urllib.request import urlretrieve
urlretrieve('https://blog.52itstyle.vip/usr/uploads/2019/06/1126271918.jpg', 'D://python_Demo//test.jpg')
  • 参考文章
  1. http://www.360doc.com/content/14/0816/15/17265359_402375821.shtml
  2. https://blog.csdn.net/weixin_37598106/article/details/72847394
  3. https://blog.csdn.net/qq_41293711/article/details/81319049

你可能感兴趣的:(python,Python,入门)