使用urllib库

  1. import urllib.request
  2. import os ,stat
  3. url = "https://cn.bing.com/th?id=OHR.Lidong2019_ZH-CN0761273672_1920x1080.jpg"
  4. try:
  5. urllib.request.urlretrieve(url,filename="/home/baixiaoxu/desk/123.jpg")
  6. except IOError as e:
  7. print("IOE ERROR")
  8. except Exception as e:
  9. print("Exception")
  10. 注意:
  11. 1,获取地址,判断地址是否存在
  12. 2,本地保存地址,判断存在
  13. 3,获取远程地址的图片名,或改名
  14. """
  15. url = "https://cn.bing.com/th?id=OHR.Lidong2019_ZH-CN0761273672_1920x1080.jpg"
  16. file_suffix = os.path.split(url)[1][-20:-1]
  17. print(file_suffix)
  18. """
  1. import urllib.request
  2. import os ,stat
  3. req = urllib.request.Request(url)
  4. file = "/home/baixiaoxu/desk/file-ttttt.jpg"
  5. req.add_header(\'User-Agent\',\'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0\')
  6. response = urllib.request.urlopen(url)
  7. html = response.read()
  8. with open(file, \'wb\') as f:
  9. f.write(html)
  1. import os
  2. os.makedirs(\'./image/\', exist_ok=True)
  3. IMAGE_URL = "http://image.nationalgeographic.com.cn/2017/1122/20171122113404332.jpg"
  4. def urllib_download():
  5. from urllib.request import urlretrieve
  6. urlretrieve(IMAGE_URL, \'./image/img1.png\')
  7. def request_download():
  8. import requests
  9. r = requests.get(IMAGE_URL)
  10. with open(\'./image/img2.png\', \'wb\') as f:
  11. f.write(r.content)
  12. def chunk_download():
  13. import requests
  14. r = requests.get(IMAGE_URL, stream=True)
  15. with open(\'./image/img3.png\', \'wb\') as f:
  16. for chunk in r.iter_content(chunk_size=32):
  17. f.write(chunk)
  1. import urllib
  2. from urllib import request
  3. import re
  4. response = request.urlopen(\'https://cn.bing.com/\')
  5. html = response.read()
  6. ht = html.decode()
  7. pattern = r\'bgLink(.*?\.jpg)\'
  8. compile_re = re.compile(pattern)
  9. hh = compile_re.findall(ht)
  10. url = hh[0].split(\'/\')[1]
  11. download = \'https://cn.bing.com/\' + url
  12. urllib.request.urlretrieve(download,filename="/home/baixiaoxu/desk/download.jpg")

版权声明:本文为g2thend原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/g2thend/p/11818599.html