首页 > 编程 > Python > 正文

python3之微信文章爬虫实例讲解

2020-02-16 01:50:11
字体:
来源:转载
供稿:网友

前提:

python3.4

windows

作用:通过搜狗的微信搜索接口http://weixin.sogou.com/来搜索相关微信文章,并将标题及相关链接导入Excel表格中

说明:需xlsxwriter模块,另程序编写时间为2017/7/11,以免之后程序无法使用可能是网站做过相关改变,程序较为简单,除去注释40多行。

正题:

思路:打开初始Url --> 正则获取标题及链接 --> 改变page循环第二步 --> 将得到的标题及链接导入Excel

爬虫的第一步都是先手工操作一遍(闲话)

进入上面提到的网址,如输入:“图片识别”,搜索,网址变为“http://weixin.sogou.com/weixin?type=2&query=%E5%9B%BE%E7%89%87%E8%AF%86%E5%88%AB&ie=utf8&s_from=input&_sug_=n&_sug_type_=1&w=01015002&oq=&ri=4&sourceid=sugg&sut=0&sst0=1499778531195&lkt=0%2C0%2C0&p=40040108”标红为重要参数,type=1时是搜索公众号,暂且不管,query=‘搜索关键词',关键词已经被编码,还有一个隐藏参数page=1

当你跳到第二页时可以看到“http://weixin.sogou.com/weixin?oq=&query=%E5%9B%BE%E7%89%87%E8%AF%86%E5%88%AB&_sug_type_=1&sut=0&lkt=0%2C0%2C0&s_from=input&ri=4&_sug_=n&type=2&sst0=1499778531195&page=2&ie=utf8&p=40040108&dp=1&w=01015002&dr=1”

好了,url可以得到了

url = 'http://weixin.sogou.com/weixin?type=2&query='+search+'&page='+str(page)

search是要搜索的关键词,用quote()编码即可插入

search = urllib.request.quote(search)

page是用来循环的

for page in range(1,pagenum+1): url = 'http://weixin.sogou.com/weixin?type=2&query='+search+'&page='+str(page)

完整的url已经得到了,接下来访问url,获得其中的数据(创建opener对象,添加header())

import urllib.request header = ('User-Agent','Mozilla/5.0') opener = urllib.request.build_opener() opener.addheaders = [header] urllib.request.install_opener(opener) data = urllib.request.urlopen(url).read().decode()

得到页面内容,采用正则表达获取相关数据

 import re  finddata = re.compile('<a target="_blank" href="(.*?)" rel="external nofollow" rel="external nofollow" .*?uigs="article_title_.*?">(.*?)</a>').findall(data)  #finddata = [('',''),('','')]

通过正则获取的数据中存在干扰项(链接:‘amp;')和无关项(标题:'<em><...><....></em>'),用replace()解决

 title = title.replace('<em><!--red_beg-->','') title = title.replace('<!--red_end--></em>','') link = link.replace('amp;','')

将处理后的标题和链接保存在列表中

 title_link.append(link) title_link.append(title)

如此搜索的标题和链接都得到了,接下来导入Excel

先创建Excel

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表