深圳哪些公司需要做网站,沈阳微网站制作,重庆网站建设培训机构,网站黏度1.使用 urlretrieve
最最最简单#xff01;#xff01;#xff01;#xff01;
from urllib.request import urlretrieve
# Python 2.7.9 之后版本引入了一个新特性#xff1a;当你 urllib.urlopen一个 http s的时候会验证一次 SSL 证书 #xff0c;当目标使用的是自签…1.使用 urlretrieve
最最最简单
from urllib.request import urlretrieve
# Python 2.7.9 之后版本引入了一个新特性当你 urllib.urlopen一个 http s的时候会验证一次 SSL 证书 当目标使用的是自签名的证书时就会爆出该错误消息
# 解决方法在全局添加如下两行代码
import ssl
ssl._create_default_https_context ssl._create_unverified_context# 爬txt文件内容
TXT_URL http://www.trustlet.org/datasets/extended_epinions/rating.txt
urlretrieve(TXT_URL, rC:\Users\10840\Downloads\rating.txt)# 爬图片
IMAGE_URL https://morvanzhou.github.io/static/img/description/learning_step_flowchart.png
urlretrieve(IMAGE_URL, rC:\Users\10840\Downloads\img.png)print(finish yeyeyey ~~~~)
2.使用 request
requests 可以更加有效率的下载大文件 比如视频等。 requests 能让你下一点, 保存一点, 而不是要全部下载完才能保存去另外的地方。这就是一个 chunk 一个 chunk 的下载。 使用 r.iter_content(chunk_size) 来控制每个 chunk 的大小, 然后在文件中写入这个 chunk 大小的数据。
import requestsIMAGE_URL https://morvanzhou.github.io/static/img/description/learning_step_flowchart.png# 无大小控制
r requests.get(IMAGE_URL)
with open(rC:\Users\10840\Downloads\img.png, wb) as f:f.write(r.content)# 使用 chunk_size 控制大小
r requests.get(IMAGE_URL, streamTrue)
with open(rC:\Users\10840\Downloads\img.png, wb) as f:for chunk in r.iter_content(chunk_size32):f.write(chunk)