python爬虫_微信公众号推送信息爬取的实例


Posted in Python onOctober 23, 2017

问题描述

利用搜狗的微信搜索抓取指定公众号的最新一条推送,并保存相应的网页至本地。

注意点

搜狗微信获取的地址为临时链接,具有时效性。

公众号为动态网页(JavaScript渲染),使用requests.get()获取的内容是不含推送消息的,这里使用selenium+PhantomJS处理

代码

#! /usr/bin/env python3
from selenium import webdriver
from datetime import datetime
import bs4, requests
import os, time, sys

# 获取公众号链接
def getAccountURL(searchURL):
 res = requests.get(searchURL)
 res.raise_for_status()
 soup = bs4.BeautifulSoup(res.text, "lxml")
 # 选择第一个链接
 account = soup.select('a[uigs="account_name_0"]')
 return account[0]['href']

# 获取首篇文章的链接,如果有验证码返回None
def getArticleURL(accountURL):
 browser = webdriver.PhantomJS("/Users/chasechoi/Downloads/phantomjs-2.1.1-macosx/bin/phantomjs")
 # 进入公众号
 browser.get(accountURL)
 # 获取网页信息
 html = browser.page_source
 accountSoup = bs4.BeautifulSoup(html, "lxml")
 time.sleep(1)
 contents = accountSoup.find_all(hrefs=True)
 try:
  partitialLink = contents[0]['hrefs']
  firstLink = base + partitialLink
 except IndexError:
  firstLink = None 
  print('CAPTCHA!')
 return firstLink

# 创建文件夹存储html网页,以时间命名
def folderCreation():
 path = os.path.join(os.getcwd(), datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
 try:
  os.makedirs(path)
 except OSError as e:
  if e.errno != errno.EEXIST:
   raise
  print("folder not exist!")
 return path

# 将html页面写入本地
def writeToFile(path, account, title):
 myfile = open("{}/{}_{}.html".format(path, account, title), 'wb')
 myfile.write(res.content)
 myfile.close()

base ='https://mp.weixin.qq.com'
accountList = ['央视新闻', '新浪新闻','凤凰新闻','羊城晚报']
query = 'http://weixin.sogou.com/weixin?type=1&s_from=input&query='

path = folderCreation()

for index, account in enumerate(accountList):
 searchURL = query + account
 accountURL = getAccountURL(searchURL)
 time.sleep(10)
 articleURL = getArticleURL(accountURL)
 if articleURL != None:
  print("#{}({}/{}): {}".format(account, index+1, len(accountList), accountURL))
  # 读取第一篇文章内容
  res = requests.get(articleURL)
  res.raise_for_status()
  detailPage = bs4.BeautifulSoup(res.text, "lxml")
  title = detailPage.title.text
  print("标题: {}\n链接: {}\n".format(title, articleURL))
  writeToFile(path, account, title)
 else:
  print('{} files successfully written to {}'.format(index, path))
  sys.exit()

print('{} files successfully written to {}'.format(len(accountList), path))

参考输出

Terminal输出

python爬虫_微信公众号推送信息爬取的实例

Finder

python爬虫_微信公众号推送信息爬取的实例

分析

链接获取

首先进入搜狗的微信搜索页面,在地址栏中提取需要的部分链接,字符串连接公众号名称,即可生成请求链接

针对静态网页,利用requests获取html文件,再用BeautifulSoup选择需要的内容

针对动态网页,利用selenium+PhantomJS获取html文件,再用BeautifulSoup选择需要的内容

遇到验证码(CAPTCHA),输出提示。此版本代码没有对验证码做实际处理,需要人为访问后,再跑程序,才能避开验证码。

文件写入

使用os.path.join()构造存储路径可以提高通用性。比如Windows路径分隔符使用back slash(\), 而OS X 和 Linux使用forward slash(/),通过该函数能根据平台进行自动转换。

open()使用b(binary mode)参数同样为了提高通用性(适应Windows)

使用datetime.now()获取当前时间进行命名,并通过strftime()格式化时间(函数名中的f代表format),

具体使用参考下表(摘自 Automate the Boring Stuff with Python)

python爬虫_微信公众号推送信息爬取的实例

以上这篇python爬虫_微信公众号推送信息爬取的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python 变量类型及命名规则介绍
Jun 08 Python
python根据文件大小打log日志
Oct 09 Python
Python中的作用域规则详解
Jan 30 Python
python生成随机mac地址的方法
Mar 16 Python
创建pycharm的自定义python模板方法
May 23 Python
我们为什么要减少Python中循环的使用
Jul 10 Python
django将数组传递给前台模板的方法
Aug 06 Python
python自动循环定时开关机(非重启)测试
Aug 26 Python
浅谈python量化 双均线策略(金叉死叉)
Jun 03 Python
Numpy 多维数据数组的实现
Jun 18 Python
浅析python 通⽤爬⾍和聚焦爬⾍
Sep 28 Python
基于python爬取链家二手房信息代码示例
Oct 21 Python
Python 模拟员工信息数据库操作的实例
Oct 23 #Python
Scrapy爬虫实例讲解_校花网
Oct 23 #Python
Python学习笔记之if语句的使用示例
Oct 23 #Python
Django实现快速分页的方法实例
Oct 22 #Python
python使用SMTP发送qq或sina邮件
Oct 21 #Python
python爬虫headers设置后无效的解决方法
Oct 21 #Python
Python 结巴分词实现关键词抽取分析
Oct 21 #Python
You might like
php模拟js函数unescape的函数代码
2012/10/20 PHP
PHP获取指定函数定义在哪个文件中以及其所在的行号实例
2014/05/08 PHP
php动态生成缩略图并输出显示的方法
2015/04/20 PHP
PHP 中提示undefined index如何解决(多种方法)
2016/03/16 PHP
php设计模式之策略模式应用案例详解
2019/06/17 PHP
php实现获取近几日、月时间示例
2019/07/06 PHP
js版本A*寻路算法
2006/12/22 Javascript
JQuery读取XML文件数据并显示的实现代码
2009/12/16 Javascript
JQuery判断HTML元素是否存在的两种解决方法
2013/12/26 Javascript
深入理解JSON数据源格式
2014/01/10 Javascript
thinkphp 表名 大小写 窍门
2015/02/01 Javascript
JS点击链接后慢慢展开隐藏着图片的方法
2015/02/17 Javascript
node.js+captchapng+jsonwebtoken实现登录验证示例
2017/08/17 Javascript
jquery+ajaxform+springboot控件实现数据更新功能
2018/01/22 jQuery
vue 指定组件缓存实例详解
2018/04/01 Javascript
VsCode与Node.js知识点详解
2019/09/05 Javascript
WebPack工具运行原理及入门教程
2020/12/02 Javascript
简单的Python抓taobao图片爬虫
2014/10/26 Python
在Python3中初学者应会的一些基本的提升效率的小技巧
2015/03/31 Python
linux环境下的python安装过程图解(含setuptools)
2017/11/22 Python
Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
2018/03/19 Python
windows下python安装pip图文教程
2018/05/25 Python
Python远程视频监控程序的实例代码
2019/05/05 Python
windows中安装Python3.8.0的实现方法
2019/11/19 Python
python filecmp.dircmp实现递归比对两个目录的方法
2020/05/22 Python
pytorch 常用函数 max ,eq说明
2020/06/28 Python
Python下载的11种姿势(小结)
2020/11/18 Python
CSS3关于z-index不生效问题的解决
2020/02/19 HTML / CSS
CSS3实现菜单悬停效果
2020/11/17 HTML / CSS
德国PC硬件网站:CASEKING
2016/10/20 全球购物
Java Servlet API中forward() 与redirect()的区别
2014/04/20 面试题
心理健康课教学反思
2014/02/13 职场文书
公司人事任命通知
2015/04/20 职场文书
python数据可视化使用pyfinance分析证券收益示例详解
2021/11/20 Python
nginx之queue的具体使用
2022/06/28 Servers
httpclient调用远程接口的方法
2022/08/14 Java/Android