[Python爬虫] 之十五:Selenium +phantomjs根据微信公众号抓取微信文章
借助搜索微信搜索引擎进行抓取
抓取过程
1、首先在搜狗的微信搜索页面测试一下,这样能够让我们的思路更加清晰

在搜索引擎上使用微信公众号英文名进行“搜公众号”操作(因为公众号英文名是公众号唯一的,而中文名可能会有重复,同时公众号名字一定要完全正确,不然可能搜到很多东西,这样我们可以减少数据的筛选工作,
只要找到这个唯一英文名对应的那条数据即可),即发送请求到'http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&_sug_=n&_sug_type_= ' % 'Python',并从页面中解析出搜索结果公众号对应的主页跳转链接。
在抓取过程中用到了pyquery 也可以用xpath

文件保存:

完整代码如下:
# coding: utf-8
# 这三行代码是防止在python2上面编码错误的,在python3上面不要要这样设置
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from urllib import quote
from pyquery import PyQuery as pq
from selenium import webdriver
from pyExcelerator import * # 导入excel相关包 import requests
import time
import re
import json
import os class wx_spider:
def __init__(self,Wechat_PublicID):
'''
构造函数,借助搜狗微信搜索引擎,根据微信公众号获取微信公众号对应的文章的,发布时间、文章标题, 文章链接, 文章简介等信息
:param Wechat_PublicID: 微信公众号
'''
self.Wechat_PublicID = Wechat_PublicID
#搜狗引擎链接url
self.sogou_search_url = 'http://weixin.sogou.com/weixin?type=1&query=%s&ie=utf8&s_from=input&_sug_=n&_sug_type_=' % quote(Wechat_PublicID) # 爬虫伪装头部设置
self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'} # 超时时长
self.timeout = 5 # 爬虫模拟在一个request.session中完成
self.session = requests.Session() # excel 第一行数据
self.excel_headData = [u'发布时间', u'文章标题', u'文章链接', u'文章简介'] # 定义excel操作句柄
self.excle_Workbook = Workbook() def log(self, msg):
'''
日志函数
:param msg: 日志信息
:return:
'''
print u'%s: %s' % (time.strftime('%Y-%m-%d %H-%M-%S'), msg) def run(self): #Step 0 : 创建公众号命名的文件夹
if not os.path.exists(self.Wechat_PublicID):
os.makedirs(self.Wechat_PublicID) # 第一步 :GET请求到搜狗微信引擎,以微信公众号英文名称作为查询关键字
self.log(u'开始获取,微信公众号英文名为:%s' % self.Wechat_PublicID)
self.log(u'开始调用sougou搜索引擎') self.log(u'搜索地址为:%s' % self.sogou_search_url)
sougou_search_html = self.session.get(self.sogou_search_url, headers=self.headers, timeout=self.timeout).content # 第二步:从搜索结果页中解析出公众号主页链接
doc = pq(sougou_search_html)
# 通过pyquery的方式处理网页内容,类似用beautifulsoup,但是pyquery和jQuery的方法类似,找到公众号主页地址
wx_url = doc('div[class=txt-box]')('p[class=tit]')('a').attr('href')
self.log(u'获取wx_url成功,%s' % wx_url) # 第三步:Selenium+PhantomJs获取js异步加载渲染后的html
self.log(u'开始调用selenium渲染html')
browser = webdriver.PhantomJS()
browser.get(wx_url)
time.sleep(3)
# 执行js得到整个页面内容
selenium_html = browser.execute_script("return document.documentElement.outerHTML")
browser.close() # 第四步: 检测目标网站是否进行了封锁
' 有时候对方会封锁ip,这里做一下判断,检测html中是否包含id=verify_change的标签,有的话,代表被重定向了,提醒过一阵子重试 '
if pq(selenium_html)('#verify_change').text() != '':
self.log(u'爬虫被目标网站封锁,请稍后再试')
else:
# 第五步: 使用PyQuery,从第三步获取的html中解析出公众号文章列表的数据
self.log(u'调用selenium渲染html完成,开始解析公众号文章')
doc = pq(selenium_html) articles_list = doc('div[class="weui_media_box appmsg"]')
articlesLength = len(articles_list)
self.log(u'抓取到微信文章%d篇' % articlesLength) # Step 6: 把微信文章数据封装成字典的list
self.log(u'开始整合微信文章数据为字典') # 遍历找到的文章,解析里面的内容
if articles_list:
index = 0 # 以当前时间为名字建表
excel_sheet_name = time.strftime('%Y-%m-%d')
excel_content = self.excle_Workbook.add_sheet(excel_sheet_name)
colindex = 0
columnsLength = len(self.excel_headData)
for data in self.excel_headData:
excel_content.write(0, colindex, data)
colindex += 1
for article in articles_list.items():
self.log(' ' )
self.log(u'开始整合(%d/%d)' % (index, articlesLength))
index += 1
# 处理单个文章
# 获取标题
title = article('h4[class="weui_media_title"]').text().strip()
self.log(u'标题是: %s' % title)
# 获取标题对应的地址
url = 'http://mp.weixin.qq.com' + article('h4[class="weui_media_title"]').attr('hrefs')
self.log(u'地址为: %s' % url)
# 获取概要内容
# summary = article('.weui_media_desc').text()
summary = article('p[class="weui_media_desc"]').text()
self.log(u'文章简述: %s' % summary)
# 获取文章发表时间
# date = article('.weui_media_extra_info').text().strip()
date = article('p[class="weui_media_extra_info"]').text().strip()
self.log(u'发表时间为: %s' % date)
# # 获取封面图片
# pic = article('.weui_media_hd').attr('style')
#
# p = re.compile(r'background-image:url(.+)')
# rs = p.findall(pic)
# if len(rs) > 0:
# p = rs[0].replace('(', '')
# p = p.replace(')', '')
# self.log(u'封面图片是:%s ' % p)
tempContent = [date, title, url, summary]
for j in range(columnsLength):
excel_content.write(index, j, tempContent[j]) self.excle_Workbook.save(self.Wechat_PublicID + '/' + self.Wechat_PublicID + '.xlsx') self.log(u'保存完成,程序结束') if __name__ == '__main__': wx_spider("python6359").run()
[Python爬虫] 之十五:Selenium +phantomjs根据微信公众号抓取微信文章的更多相关文章
- [Python爬虫] 之三十:Selenium +phantomjs 利用 pyquery抓取栏目
一.介绍 本例子用Selenium +phantomjs爬取栏目(http://tv.cctv.com/lm/)的信息 二.网站信息 三.数据抓取 首先抓取所有要抓取网页链接,共39页,保存到数据库里 ...
- [Python爬虫] 之十:Selenium +phantomjs抓取活动行中会议活动
一.介绍 本例子用Selenium +phantomjs爬取活动树(http://www.huodongshu.com/html/find_search.html?search_keyword=数字) ...
- 第三百三十节,web爬虫讲解2—urllib库爬虫—实战爬取搜狗微信公众号—抓包软件安装Fiddler4讲解
第三百三十节,web爬虫讲解2—urllib库爬虫—实战爬取搜狗微信公众号—抓包软件安装Fiddler4讲解 封装模块 #!/usr/bin/env python # -*- coding: utf- ...
- 九 web爬虫讲解2—urllib库爬虫—实战爬取搜狗微信公众号—抓包软件安装Fiddler4讲解
封装模块 #!/usr/bin/env python # -*- coding: utf-8 -*- import urllib from urllib import request import j ...
- [Python爬虫] 之十三:Selenium +phantomjs抓取活动树会议活动数据
抓取活动树网站中会议活动数据(http://www.huodongshu.com/html/index.html) 具体的思路是[Python爬虫] 之十一中抓取活动行网站的类似,都是用多线程来抓取, ...
- [Python爬虫] 之三十一:Selenium +phantomjs 利用 pyquery抓取消费主张信息
一.介绍 本例子用Selenium +phantomjs爬取央视栏目(http://search.cctv.com/search.php?qtext=消费主张&type=video)的信息(标 ...
- [Python爬虫] 之九:Selenium +phantomjs抓取活动行中会议活动(单线程抓取)
思路是这样的,给一系列关键字:互联网电视:智能电视:数字:影音:家庭娱乐:节目:视听:版权:数据等.在活动行网站搜索页(http://www.huodongxing.com/search?city=% ...
- [Python爬虫] 之十一:Selenium +phantomjs抓取活动行中会议活动信息
一.介绍 本例子用Selenium +phantomjs爬取活动行(http://www.huodongxing.com/search?qs=数字&city=全国&pi=1)的资讯信息 ...
- [Python爬虫] 之十七:Selenium +phantomjs 利用 pyquery抓取梅花网数据
一.介绍 本例子用Selenium +phantomjs爬取梅花网(http://www.meihua.info/a/list/today)的资讯信息,输入给定关键字抓取资讯信息. 给定关键字:数字: ...
随机推荐
- Linux 基础——查看文件内容的命令
第四天,继续学习.今天看到一句话,"你以为你以为的就是你以为的吗?",这句话还是有点意思啊!!! 一.查看文件内容的命令 file dest:查看文件的类型.在Linux中,文件的 ...
- AC日记——[SDOI2009]HH去散步 洛谷 P2151
[SDOI2009]HH去散步 思路: 矩阵快速幂递推(类似弗洛伊德): 给大佬跪烂-- 代码: #include <bits/stdc++.h> using namespace std; ...
- Team Service 编译项目并生成项目
第一步:生成GitHub帐号连接 在Service中选择Github 在弹出的GitHub连接中点击授权,即会弹出另一个窗口,输入Github的用户名及口令,即可授权. 第二步:创建Build定义 解 ...
- NHibernate框架与BLL+DAL+Model+Controller+UI 多层架构十分相似--『Spring.NET+NHibernate+泛型』概述、知识准备及介绍(一)
原文://http://blog.csdn.net/wb09100310/article/details/47271555 1. 概述 搭建了Spring.NET+NHibernate的一个数据查询系 ...
- LOJ #6284. 数列分块入门 8-分块(区间查询等于一个数c的元素,并将这个区间的所有元素改为c)
#6284. 数列分块入门 8 内存限制:256 MiB时间限制:500 ms标准输入输出 题目类型:传统评测方式:文本比较 上传者: hzwer 提交提交记录统计测试数据讨论 2 题目描述 给出 ...
- vmware漏洞之三——Vmware虚拟机逃逸漏洞(CVE-2017-4901)Exploit代码分析与利用
本文简单分析了代码的结构.有助于理解. 转:http://www.freebuf.com/news/141442.html 0×01 事件分析 2017年7月19 unamer在其github上发布了 ...
- HDU 1829 A Bug's Life 【带权并查集/补集法/向量法】
Background Professor Hopper is researching the sexual behavior of a rare species of bugs. He assumes ...
- CodeForces 738A Interview with Oleg
模拟. #pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #includ ...
- POJ2912 Rochambeau [扩展域并查集]
题目传送门 Rochambeau Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 4463 Accepted: 1545 ...
- 苹果Itools
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha