本文共 1305 字,大约阅读时间需要 4 分钟。
大家用爬虫下载图片时肯定遇到过https://demo?wx_fmt=jpeg链接的图片,常见的就是微信公众号的图片。
遇到链接图片用普通的方式是无法爬取下来的,我们可以用urllib.request进行简单爬取,具体源码如下:# 2018年10月07日 13点30分# 作者:cacho_37967865# 爬虫:抓取微信公众号图片# 示例网址:https://mp.weixin.qq.com/s/2Bi__FPfSMSli0pw6GtSAQfrom re import findallfrom urllib.request import urlopenimport osurl = 'https://mp.weixin.qq.com/s/2Bi__FPfSMSli0pw6GtSAQ'image_path = './Wechatimg'os.chdir(image_path)# bytes->str:decode 解码with urlopen(url) as fp: content = fp.read().decode() # 需要进行解码成字符串print(content) # 得到的是默认的utf-8格式字符串pattern = 'data-type="jpeg" data-src="(.+?)"'result = findall(pattern, content)print(result) # 得到的是一个列表for index, item in enumerate(result,1): data = urlopen(str(item)).read() print('开始下载第' + str(index) +'张图片:'+ str(item)) f = open(str(index) + '.jpg', "wb") f.write(data) f.close()
从源码中可以看到两个特殊的函数decode()和enumerate()
1. decode()方法使用编码注册的编解码器解码该字符串。它默认是使用系统默认的字符串编码。 str->bytes:encode 编码 bytes->str:decode 解码 bytes.decode(encoding="utf-8", errors="strict") str.encode(encoding="utf-8", errors="strict") 编码就是将字符串转换成字节码,涉及到字符串的内部表示。 解码就是将字节码转换为字符串,将比特位显示成字符。2. enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
用法 enumerate(sequence, [start=0])参数 sequence -- 一个序列、迭代器或其他支持迭代对象。 start -- 下标起始位置,默认没有时以0开始转载地址:http://hegii.baihongyu.com/