利用搜狗的微信搜索抓取指定公众号的最新一条推送,并保存相应的网页至本地。html
临时连接
,具备时效性。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[1]['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): pathToWrite = os.path.join(path, '{}_{}.html'.format(account, title)) myfile = open(pathToWrite, '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))
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)enumerate
的使用: https://stackoverflow.com/questions/3162271/get-loop-count-inside-a-python-for-loopopen()
使用b
参数理由: https://stackoverflow.com/questions/2665866/what-is-the-wb-mean-in-this-code-using-python