簡單直接上:
原理:
利用搜狗搜尋通路指定公衆号,獲得公衆号最新的前10篇文章,
注意需要利用select +PhantomJS 加載js 的内容,以及‘&’的轉義(代碼後附上特殊符号轉義)
缺點:
隻能擷取到最新的10篇文章,若需要擷取所有曆史文章,可以通過微信公衆平台的方法擷取,網上有解決方案
# encoding=utf8
# @Author : LYG
# @Time : 2019/2/13 11:16
# @Name : CrawlWechat.py
from bs4 import BeautifulSoup
from urllib2 import urlopen
from selenium import webdriver
def get_url():
'''
通過搜狗搜尋,擷取指定公衆号的最新連結
url : 搜尋連結
:return:
new_url : 指定公衆号的最新連結
'''
# 修改query的參數即可(支援中文修改),也可以直接通路域名帶data就好
# type=1 指明是搜尋公衆号,type=0 指明是搜尋文章
url = "https://weixin.sogou.com/weixin?type=1&s_from=input&query=Linux公社&ie=utf8&_sug_=n&_sug_type_="
page = urlopen(url)
html = page.read()
soup = BeautifulSoup(html,'lxml')
node = soup.select('a[uigs="account_name_0"]')
new_url = node[0]['href']
return new_url
def get_content():
'''
拿到公衆号裡最新十篇文章的标題與URL
:return:
'''
url = get_url()
# phantomjs.exe 的絕對路徑
driver= webdriver.PhantomJS(executable_path=r"D:\python\venv\Lib\site-packages\selenium\webdriver\phantomjs\phantomjs-2.1.1-windows\phantomjs-2.1.1-windows\bin\phantomjs.exe")
driver.get(url)
html = driver.page_source
result_url = []
result_title = []
soup = BeautifulSoup(html, 'lxml')
titles = soup.select("h4.weui_media_title")
for title in titles:
result_title.append(title.text)
# & 符号轉義 & = &
result_url.append("https://mp.weixin.qq.com"+title['hrefs'].replace('&','&'))
with open('a.txt','w') as f:
for i in range(len(result_url)):
f.write("%s %s"%(result_title[i].encode('utf-8'),result_url[i].encode('utf-8')))
f.write('\n')
driver.quit()
if __name__ == '__main__':
get_content()
#get_url()
