python 微信爬虫_Python爬虫实战(三) — 微信文章爬虫
前言
最近烦心事挺多的,能让我得到快乐的是一行行能够运行的代码,那么今天为大家带来微信文章爬取实战。
本篇目标
根据关键词搜索微信文章,并提取文章链接
自动保存微信文章,并保存为HTML格式
实现设置提取文章数目,并提供有关交互操作
快速开始
1.确定URL链接格式
首先打开搜狗微信搜索平台,任意搜索一个感兴趣的关键词,观察网址http://weixin.sogou.com/weixin?type=2&query=%E5%B0%8F%E7%B1%B3&ie=utf8&s_from=input&_sug_=n&_sug_type_=1&w=01015002&oq=&ri=0&sourceid=sugg&sut=0&sst0=1520605349656&lkt=0%2C0%2C0&p=40040108
这里我输入的是小米,可以观察到,链接中type字段控制检索信息类型,query字段则对应于我们的关键词,因为会自动编码,所以我看看到的是%E5...类似信息,其他内容则是无关信息,这里我们不讨论,下面点击下一页,
http://weixin.sogou.com/weixin?oq=&query=%E5%B0%8F%E7%B1%B3&_sug_type_=1&sut=0&lkt=0%2C0%2C0&s_from=input&ri=0&_sug_=n&type=2&sst0=1520605349656&page=2&ie=utf8&p=40040108&dp=1&w=01015002&dr=1
观察到链接中多出了一个page字段,对应于数字2,猜测这就是页码,尝试之后,果不其然,我们的猜测是正确的,下面我们来爬取文章的具体内容
2.提取文章地址
点击F12,通过控制台,我们发现文章网址对应在,txt-box元素下,如图
由此,我们很容易的写出我们的匹配模式代码
'
对应完整代码如下:
def getlisturl(key, pagestart, pageend):
try:
page = pagestart
keycode = urllib.request.quote(key)
pagecode = urllib.request.quote("&page")
for page in range(pagestart, pageend+1):
url = "http://weixin.sogou.com/weixin?type=2&query=" + keycode + pagecode + str(page)
data1 = downloader(url)
listurlpat = '
data2 = re.compile(listurlpat, re.S)
result = data2.findall(data1)
listurl.append(result)
#print(listurl)
print("共获取到" + str(len(listurl)) + "页")
return listurl
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
time.sleep(10)
except Exception as e:
print("exception:" + str(e))
time.sleep(1)
其中,key对应于关键词,pagestart对应于起始页码,默认为第一页,pageend对应于终止页码。
下载模块
我们需要从对应链接中下载内容,才能做到后面内容的提取,这里,下载模块我提供了两种方案,一种使用了代理服务器,一种没有使用,下面是没有使用代理服务器的代码:
def downloader(url):
headers = ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 "
"Core/1.63.4793.400 QQBrowser/10.0.702.400")
opener = urllib.request.build_opener()
opener.addheaders = [headers]
urllib.request.install_opener(opener)
try:
data = urllib.request.urlopen(url).read()
data = data.decode('utf-8')
return data
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
time.sleep(10)
except Exception as e:
print("exception:" + str(e))
time.sleep(1)
这里使用了一些简单的伪装,以防止微信对爬虫的阻止,但这样并不安全,所以在完整代码中还提供了代理服务器模块,但是因为免费的代理服务器几乎都不能用,所以在此不多讲解。
完整代码如下
import re
import urllib.request
import time
import urllib.error
'''
def use_proxy(proxy_addr, url):
headers = ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 "
"Core/1.63.4793.400 QQBrowser/10.0.702.400")
opener = urllib.request.build_opener()
opener.addheaders = [headers]
urllib.request.install_opener(opener)
try:
proxy = urllib.request.ProxyHandler({'http':proxy_addr})
opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)
urllib.request.install_opener(opener)
data = urllib.request.urlopen(url).read().decode('utf-8')
return data
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
time.sleep(10)
except Exception as e:
print("exception:" + str(e))
time.sleep(1)
'''
def downloader(url):
headers = ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 "
"Core/1.63.4793.400 QQBrowser/10.0.702.400")
opener = urllib.request.build_opener()
opener.addheaders = [headers]
urllib.request.install_opener(opener)
try:
data = urllib.request.urlopen(url).read()
data = data.decode('utf-8')
return data
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
time.sleep(10)
except Exception as e:
print("exception:" + str(e))
time.sleep(1)
def getlisturl(key, pagestart, pageend):
try:
page = pagestart
keycode = urllib.request.quote(key)
pagecode = urllib.request.quote("&page")
for page in range(pagestart, pageend+1):
url = "http://weixin.sogou.com/weixin?type=2&query=" + keycode + pagecode + str(page)
data1 = downloader(url)
listurlpat = '
data2 = re.compile(listurlpat, re.S)
result = data2.findall(data1)
listurl.append(result)
#print(listurl)
print("共获取到" + str(len(listurl)) + "页")
return listurl
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
time.sleep(10)
except Exception as e:
print("exception:" + str(e))
time.sleep(1)
def getcontent(listurl):
i = 0
html1 = '''
微信文章页面
fh = open("C://Users/59574/Desktop/python/test/WeChatSpider/1.html", "wb")
fh.write(html1.encode("utf-8"))
fh.close()
fh = open("C://Users/59574/Desktop/python/test/WeChatSpider/1.html", "ab")
for i in range(0, len(listurl)):
for j in range(0, len(listurl[i])):
try:
url = listurl[i][j]
url = url.replace("amp;", "")
data = downloader(url)
titlepat = "
(.*?)"
contentpat = 'id="js_content">(.*?)id="js_sg_bar"'
title = re.compile(titlepat).findall(data)
content = re.compile(contentpat, re.S).findall(data)
if (title != []):
thistitle = title[0]
if (content != []):
thiscontent = content[0]
dataall = "
标题为:" + thistitle + "
内容为:" + thiscontent + "
"
fh.write(dataall.encode("utf-8"))
print("第"+str(i+1) + "个网页第" + str(j+1) + "条内容保存")
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
time.sleep(10)
except Exception as e:
print("exception:" + str(e))
time.sleep(1)
fh.close()
html2 = '''
'''
fh = open("C://Users/59574/Desktop/python/test/WeChatSpider/1.html", "ab")
fh.write(html2.encode("utf-8"))
fh.close()
if __name__ == '__main__':
listurl = list()
key = str(input('请输入要查询的关键词:'))
#proxy = "115.223.209.169:9000"
pagestart = 1
pageend = int(input('请输入结束页码(每页保存10条内容)'))
listurl = getlisturl(key, pagestart, pageend)
getcontent(listurl)
Github版本
运行结果
小结
开学了,事情有些多,个人的一些事情也让人难过,不过我会尽力更新,下一次我会为大家带来该代码多线程运行版本。
最后,希望大家都能尊重我的付出,转载我的文章请注明出处;
也希望大家关注我的个人博客 HD Blog
谢谢~
python 微信爬虫_Python爬虫实战(三) — 微信文章爬虫相关推荐
- 云计算Python自动化运维开发实战 三、python文件类型
为什么80%的码农都做不了架构师?>>> 云计算Python自动化运维开发实战 三.python文件类型 导语: python常用的有3种文件类型 1. 源代码 py ...
- 微信小程序开发实战11_4 微信支付退款流程
当交易发生之后一年内,由于买家或者卖家的原因需要退款时,卖家可以通过退款接口将支付金额退还给买家,微信支付将收到退款请求并且验证成功之后,将支付款按原路退还至买家账号上.使用该接口时的一些注意事项如下 ...
- python微信公众号爬虫_Python爬取指定微信公众号所有文章!
篇文章使用到的技术: mitmdump + 电脑版微信 先分析打开可视化抓包工具, 勾选https代理.然后打开电脑版微信 任意点击一个公众号,再点击查看历史消息 注:想学习Python的小伙伴们 可 ...
- python 小说爬虫_Python实现的爬取小说爬虫功能示例
本文实例讲述了Python实现的爬取小说爬虫功能.分享给大家供大家参考,具体如下: 想把顶点小说网上的一篇持续更新的小说下下来,就写了一个简单的爬虫,可以爬取爬取各个章节的内容,保存到txt文档中,支 ...
- 如何用python爬取公众号文章搜狗微信搜索_python抓取搜狗微信公众号文章
初学python,抓取搜狗微信公众号文章存入mysql mysql表: 代码: import requests import json import re import pymysql # 创建连接 ...
- python发送微信消息_python 发送QQ或者微信消息
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 废话少说,先上代码: # coding = utf-8 import win32gui import win32api import win32con i ...
- 用python刷微信投票_Python——开发一个自动化微信投票器【附代码实例方法】
一个研究Python实践,最近研究一个投票的东东,主要是想测试利用Python实现刷微信投票. 本文纯粹为了记录一下 webdriver直接操作页面按钮的方法: #!/usr/bin/python # ...
- python 图灵 微信 菜谱_python——wxpy模块实现微信尬聊(基于图灵机器人)-Go语言中文社区...
wxpy(微信机器人)是在itchat基础上开发的微信个人功能服务API,基本可以实现微信各种拓展功能, 支持pip安装,适用2.7以及3.4-3.6的python版本 通过# 导入模块 from w ...
- python调用微信支付_Python使用JsAPI发起微信支付 Demo
Python使用JsAPI发起微信支付 Demo 这个是基于Django框架. 了解更多,可以关注公众号"轻松学编程" 1.公众号设置.微信商户号设置 这些都可以在官网查得到, 左 ...
- 「Python爬虫系列讲解」三、正则表达式爬虫之牛刀小试
本专栏是以杨秀璋老师爬虫著作<Python网络数据爬取及分析「从入门到精通」>为主线.个人学习理解为主要内容,以学习笔记形式编写的. 本专栏不光是自己的一个学习分享,也希望能给您普及一些关 ...
最新文章
- 13.文件:因为懂你,所以永恒
- Python学习笔记:访问数据库
- 浅聊程序化世界构建流程
- 对计算机网络与系统的认识,浅谈对计算机网络的认识
- [导入]ASP.NET 2.0中Page事件的执行顺序
- 理论基础 —— 索引 —— 分块索引
- Meteor 加入账户系统
- htcvr设备计算机配置,VR对电脑配置要求高吗?HTC Vive电脑配置要求
- MATLAB说文本命令超过,MATLAB基础
- java arryalist去重复_java ArrayList去重复值
- 防毒墙APT防护抗DDOS攻击
- win10和ubuntu双系统,切换优先启动
- 设计模式之里氏宗青出于蓝而胜于蓝
- 总结个人关于雷达样式的见解(脉内脉间调制)
- 如何使用微软提供的TCHAR.H头文件?
- TorchScript (将动态图转为静态图)(模型部署)(jit)(torch.jit.trace)(torch.jit.script)
- 微信中的用户ID(openid和unionid)
- Android 屏幕旋转 全解析
- netkeeper代理服务器未响应,使用netkeeper创翼网速慢解决方案(C13)
- 解决AppBarLayout嵌套WebView滑动冲突的问题
热门文章
- 账龄分析表excel模板_这种高端表格模板你会做吗?Excel制作带照片的员工信息查询表...
- java 注释 超链接_Java注释
- 恭喜你!看到了这篇靠谱的12款CAM软件测评(下篇)
- 计算机常见的编码规范
- QQ浏览器该站点长时间无响应_消除CNZZ.站长统计代码被Chrome浏览器警告的操作...
- 回文字符串判断以及最长回文字符串长度判断
- 使用OTDR进行双向光纤测试
- idea 阿里巴巴代码规范插件使用
- 华为主题包hwt下载_hwtTool下载-华为主题开发工具下载 v9.0.2.301 官方版[百度网盘资源] - 安下载...
- 肯德尔系数怎么分析_2020LPL春季赛3月15日比赛数据的数据分析(Python)