博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Python爬虫】下载微信公众号图片
阅读量:4099 次
发布时间:2019-05-25

本文共 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/

你可能感兴趣的文章
Flutter Boost的router管理
查看>>
Vue2.0全家桶仿腾讯课堂(移动端)
查看>>
React+Redux系列教程
查看>>
19 个 JavaScript 常用的简写技术
查看>>
iOS开发支付集成之微信支付
查看>>
一个很棒的Flutter学习资源列表
查看>>
为什么你应该放弃React老的Context API用新的Context API
查看>>
Koa2初体验
查看>>
Koa 2 初体验(二)
查看>>
Koa2框架原理解析和实现
查看>>
C++模板
查看>>
【C#】如何实现一个迭代器
查看>>
【C#】利用Conditional属性完成编译忽略
查看>>
mapReduce(3)---入门示例WordCount
查看>>
hbase(3)---shell操作
查看>>
hbase(1)---概述
查看>>
hbase(5)---API示例
查看>>
SSM-CRUD(1)---环境搭建
查看>>
Nginx(2)---安装与启动
查看>>
springBoot(5)---整合servlet、Filter、Listener
查看>>