python crawler_WeChat公共帐户推送信息爬取示例
优采云 发布时间: 2020-08-07 04:12python crawler_WeChat公共帐户推送信息爬取示例
更新时间: 2017年10月23日10:03:08转载作者: ChaseChoi
下面的编辑器将为您带来python crawler_WeChat公共帐户推送信息爬取的示例. 编辑认为这还不错,因此我将与您分享并提供参考. 让我们跟随编辑器看看
问题描述
使用搜狗的微信搜索来获取指定官方帐户的最新推送,并将相应的网页保存到本地.
注释
搜狗微信获取的地址是临时链接,对时间敏感.
官方帐户是一个动态网页(由JavaScript渲染),并且使用request.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))
参考输出
端子输出
查找器
分析
获取链接
首先进入搜狗的微信搜索页面,在地址栏中提取链接的必需部分,将字符串连接到官方帐户名,然后生成请求链接
对于静态网页,请使用请求获取html文件,然后使用BeautifulSoup选择所需的内容
对于动态网页,请使用selenium + PhantomJS获取html文件,然后使用BeautifulSoup选择所需的内容
遇到验证码(CAPTCHA)时,输出提示. 此版本的代码实际上并未处理验证码,因此在运行程序之前需要手动对其进行访问,以避免验证码.
文件写入
使用os.path.join()构造存储路径可以提高通用性. 例如,Windows路径分隔符使用反斜杠(\),而OS X和Linux使用反斜杠(/). 该功能可以根据平台自动转换.
open()使用b(二进制模式)参数来提高通用性(适用于Windows)
使用datetime.now()获取当前的命名时间,并通过strftime()格式化时间(函数名称中的f表示格式),
有关特定用途,请参阅下表(摘自“使用Python自动完成钻孔”)
上面的python爬网程序_WeChat公共帐户推送信息爬网示例是编辑器共享的所有内容,希望为您提供参考,也希望可以支持脚本库.