python使用webdriver爬取微信公眾號(hào)
本文實(shí)例為大家分享了python使用webdriver爬取微信公眾號(hào)的具體代碼,供大家參考,具體內(nèi)容如下
# -*- coding: utf-8 -*-
from selenium import webdriver
import time
import json
import requests
import re
import random
#微信公眾號(hào)賬號(hào)
user=""
#公眾號(hào)密碼
password=""
#設(shè)置要爬取的公眾號(hào)列表
gzlist=['香河微服務(wù)']
#登錄微信公眾號(hào),獲取登錄之后的cookies信息,并保存到本地文本中
def weChat_login():
#定義一個(gè)空的字典,存放cookies內(nèi)容
post={}
#用webdriver啟動(dòng)谷歌瀏覽器
print("啟動(dòng)瀏覽器,打開微信公眾號(hào)登錄界面")
driver = webdriver.Chrome(executable_path='E:\\program\\chromedriver.exe')
#打開微信公眾號(hào)登錄頁面
driver.get('https://mp.weixin.qq.com/')
#等待5秒鐘
time.sleep(5)
print("正在輸入微信公眾號(hào)登錄賬號(hào)和密碼......")
#清空賬號(hào)框中的內(nèi)容
driver.find_element_by_xpath("http://*[@id=\"header\"]/div[2]/div/div/form/div[1]/div[1]/div/span/input").clear()
#自動(dòng)填入登錄用戶名
driver.find_element_by_xpath("http://*[@id=\"header\"]/div[2]/div/div/form/div[1]/div[1]/div/span/input").send_keys(user)
#清空密碼框中的內(nèi)容
driver.find_element_by_xpath("http://*[@id=\"header\"]/div[2]/div/div/form/div[1]/div[2]/div/span/input").clear()
#自動(dòng)填入登錄密碼
driver.find_element_by_xpath("http://*[@id=\"header\"]/div[2]/div/div/form/div[1]/div[2]/div/span/input").send_keys(password)
# 在自動(dòng)輸完密碼之后需要手動(dòng)點(diǎn)一下記住我
print("請(qǐng)?jiān)诘卿浗缑纥c(diǎn)擊:記住賬號(hào)")
time.sleep(10)
#自動(dòng)點(diǎn)擊登錄按鈕進(jìn)行登錄
driver.find_element_by_xpath("http://*[@id=\"header\"]/div[2]/div/div/form/div[4]/a").click()
# 拿手機(jī)掃二維碼!
print("請(qǐng)拿手機(jī)掃碼二維碼登錄公眾號(hào)")
time.sleep(20)
print("登錄成功")
#重新載入公眾號(hào)登錄頁,登錄之后會(huì)顯示公眾號(hào)后臺(tái)首頁,從這個(gè)返回內(nèi)容中獲取cookies信息
driver.get('https://mp.weixin.qq.com/')
#獲取cookies
cookie_items = driver.get_cookies()
#獲取到的cookies是列表形式,將cookies轉(zhuǎn)成json形式并存入本地名為cookie的文本中
for cookie_item in cookie_items:
post[cookie_item['name']] = cookie_item['value']
cookie_str = json.dumps(post)
with open('cookie.txt', 'w+') as f:
f.write(cookie_str)
print("cookies信息已保存到本地")
#爬取微信公眾號(hào)文章,并存在本地文本中
def get_content(query):
#query為要爬取的公眾號(hào)名稱
#公眾號(hào)主頁
url = 'https://mp.weixin.qq.com'
#設(shè)置headers
header = {
"HOST": "mp.weixin.qq.com",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0"
}
#讀取上一步獲取到的cookies
with open('cookie.txt', 'r') as f:
cookie = f.read().decode("UTF-8")
cookies = json.loads(cookie)
#登錄之后的微信公眾號(hào)首頁url變化為:https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=1849751598,從這里獲取token信息
response = requests.get(url=url, cookies=cookies)
token = re.findall(r'token=(\d+)', str(response.url))[0]
#搜索微信公眾號(hào)的接口地址
search_url = 'https://mp.weixin.qq.com/cgi-bin/searchbiz?'
#搜索微信公眾號(hào)接口需要傳入的參數(shù),有三個(gè)變量:微信公眾號(hào)token、隨機(jī)數(shù)random、搜索的微信公眾號(hào)名字
query_id = {
'action': 'search_biz',
'token' : token,
'lang': 'zh_CN',
'f': 'json',
'ajax': '1',
'random': random.random(),
'query': query,
'begin': '0',
'count': '5'
}
#打開搜索微信公眾號(hào)接口地址,需要傳入相關(guān)參數(shù)信息如:cookies、params、headers
search_response = requests.get(search_url, cookies=cookies, headers=header, params=query_id)
#取搜索結(jié)果中的第一個(gè)公眾號(hào)
lists = search_response.json().get('list')[0]
#獲取這個(gè)公眾號(hào)的fakeid,后面爬取公眾號(hào)文章需要此字段
fakeid = lists.get('fakeid')
#微信公眾號(hào)文章接口地址
appmsg_url = 'https://mp.weixin.qq.com/cgi-bin/appmsg?'
#搜索文章需要傳入幾個(gè)參數(shù):登錄的公眾號(hào)token、要爬取文章的公眾號(hào)fakeid、隨機(jī)數(shù)random
query_id_data = {
'token': token,
'lang': 'zh_CN',
'f': 'json',
'ajax': '1',
'random': random.random(),
'action': 'list_ex',
'begin': '0',#不同頁,此參數(shù)變化,變化規(guī)則為每頁加5
'count': '5',
'query': '',
'fakeid': fakeid,
'type': '9'
}
#打開搜索的微信公眾號(hào)文章列表頁
appmsg_response = requests.get(appmsg_url, cookies=cookies, headers=header, params=query_id_data)
#獲取文章總數(shù)
max_num = appmsg_response.json().get('app_msg_cnt')
#每頁至少有5條,獲取文章總的頁數(shù),爬取時(shí)需要分頁爬
num = int(int(max_num) / 5)
#起始頁begin參數(shù),往后每頁加5
begin = 0
while num + 1 > 0 :
query_id_data = {
'token': token,
'lang': 'zh_CN',
'f': 'json',
'ajax': '1',
'random': random.random(),
'action': 'list_ex',
'begin': '{}'.format(str(begin)),
'count': '5',
'query': '',
'fakeid': fakeid,
'type': '9'
}
print('正在翻頁:--------------',begin)
#獲取每一頁文章的標(biāo)題和鏈接地址,并寫入本地文本中
query_fakeid_response = requests.get(appmsg_url, cookies=cookies, headers=header, params=query_id_data)
fakeid_list = query_fakeid_response.json().get('app_msg_list')
for item in fakeid_list:
content_link=item.get('link')
content_title=item.get('title')
fileName=query+'.txt'
# with open('e://xhwfw.txt','a') as fh:
# fh.write(content_title+":\n"+content_link+"\n")
print content_title+":\n"+content_link+"\n"
num -= 1
begin = int(begin)
begin+=5
time.sleep(2)
if __name__=='__main__':
try:
#登錄微信公眾號(hào),獲取登錄之后的cookies信息,并保存到本地文本中
weChat_login()
#登錄之后,通過微信公眾號(hào)后臺(tái)提供的微信公眾號(hào)文章接口爬取文章
for query in gzlist:
#爬取微信公眾號(hào)文章,并存在本地文本中
print("開始爬取公眾號(hào):"+query)
get_content(query)
print("爬取完成")
except Exception as e:
print(str(e))
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解duck typing鴨子類型程序設(shè)計(jì)與Python的實(shí)現(xiàn)示例
這篇文章主要介紹了詳解duck typing鴨子類型程序設(shè)計(jì)與Python的實(shí)現(xiàn)示例,鴨子類型特指解釋型語言中的一種編程風(fēng)格,需要的朋友可以參考下2016-06-06
關(guān)于python線程池的四種實(shí)現(xiàn)方式
這篇文章主要介紹了關(guān)于python線程池的四種實(shí)現(xiàn)方式,一個(gè)程序運(yùn)行起來后,一定有一個(gè)執(zhí)行代碼的東西,這個(gè)東西就是線程,需要的朋友可以參考下2023-04-04
對(duì)Python 檢查文件名是否規(guī)范的實(shí)例詳解
今天小編就為大家分享一篇對(duì)Python 檢查文件名是否規(guī)范的實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-06-06
python requests 測(cè)試代理ip是否生效
這篇文章主要介紹了python requests 測(cè)試代理ip是否生效的相關(guān)資料,需要的朋友可以參考下2018-07-07
Pandas DataFrame實(shí)現(xiàn)任意位置插入一列或一行
Pandas是Python中最流行的數(shù)據(jù)處理和分析庫之一,在數(shù)據(jù)分析過程中,有時(shí)候需要在Dataframe中插入新的數(shù)據(jù)列,本文主要介紹了Pandas DataFrame實(shí)現(xiàn)任意位置插入一列或一行,具有一定的參考價(jià)值,感興趣的可以了解一下2023-08-08
Python Pandas數(shù)據(jù)分析工具用法實(shí)例
這篇文章主要介紹了Python Pandas數(shù)據(jù)分析工具用法實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11

