翻頁(yè)打開(kāi)headers,開(kāi)發(fā)工具思路首先start_url==?
優(yōu)采云 發(fā)布時(shí)間: 2021-07-18 23:25翻頁(yè)打開(kāi)headers,開(kāi)發(fā)工具思路首先start_url==?
由于微信流量封閉,微信內容比較難看。為了能夠在微信公眾號爬文章,有網(wǎng)友用python實(shí)現了。我們來(lái)看看他的實(shí)現思路和代碼。也許它可以使用?要知道微信公眾號里的內容不是百度上的收錄,能做到就太牛了。
開(kāi)發(fā)工具
思考
首先start_url=””,掃碼注冊微信公眾平臺,有的話(huà)直接忽略?huà)叽a登錄即可。(注冊個(gè)人訂閱號即可),使用selenium自動(dòng)掃碼登錄獲取cookie值,然后使用cookie進(jìn)行響應。
您需要先下載webdriver插件。插件下載谷歌瀏覽器對應的版本。下載后會(huì )得到chromedriver.exe,然后把這個(gè)chromedriver.exe和python解釋器的python.exe文件放在同一個(gè)目錄下。作為響應,取回網(wǎng)頁(yè)的源代碼并取回令牌值。令牌值具有時(shí)間敏感性。
首先打開(kāi)公眾號,點(diǎn)擊圖文編輯中的超鏈接。
使用python爬取微信公眾號文章
使用python爬取微信公眾號文章
使用python爬取微信公眾號文章
按F12查看公眾號對應的fakeid值。
使用python爬取微信公眾號文章
使用python爬取微信公眾號文章
翻頁(yè)打開(kāi)headers,取回首頁(yè)url地址
第二頁(yè)地址
找到模式,上傳代碼
# !/usr/bin/nev python
# -*-coding:utf8-*-
import tkinter as tk
from selenium import webdriver
import time, re, jsonpath, xlwt
from requests_html import HTMLSession
session = HTMLSession()
class GZHSpider(object):
def __init__(self):
"""定義可視化窗口,并設置窗口和主題大小布局"""
self.window = tk.Tk()
self.window.title('公眾號信息采集')
self.window.geometry('800x600')
"""創(chuàng )建label_user按鈕,與說(shuō)明書(shū)"""
self.label_user = tk.Label(self.window, text='需要爬取的公眾號:', font=('Arial', 12), width=30, height=2)
self.label_user.pack()
"""創(chuàng )建label_user關(guān)聯(lián)輸入"""
self.entry_user = tk.Entry(self.window, show=None, font=('Arial', 14))
self.entry_user.pack(after=self.label_user)
"""創(chuàng )建label_passwd按鈕,與說(shuō)明書(shū)"""
self.label_passwd = tk.Label(self.window, text="爬取多少頁(yè):(小于100)", font=('Arial', 12), width=30, height=2)
self.label_passwd.pack()
"""創(chuàng )建label_passwd關(guān)聯(lián)輸入"""
self.entry_passwd = tk.Entry(self.window, show=None, font=('Arial', 14))
self.entry_passwd.pack(after=self.label_passwd)
"""創(chuàng )建Text富文本框,用于按鈕操作結果的展示"""
self.text1 = tk.Text(self.window, font=('Arial', 12), width=85, height=22)
self.text1.pack()
"""定義按鈕1,綁定觸發(fā)事件方法"""
self.button_1 = tk.Button(self.window, text='爬取', font=('Arial', 12), width=10, height=1,
command=self.parse_hit_click_1)
self.button_1.pack(before=self.text1)
"""定義按鈕2,綁定觸發(fā)事件方法"""
self.button_2 = tk.Button(self.window, text='清除', font=('Arial', 12), width=10, height=1,
command=self.parse_hit_click_2)
self.button_2.pack(anchor="e")
def parse_hit_click_1(self):
"""定義觸發(fā)事件1,調用main函數"""
user_name = self.entry_user.get()
pass_wd = int(self.entry_passwd.get())
self.main(user_name, pass_wd)
def main(self, user_name, pass_wd):
# 網(wǎng)頁(yè)登錄
driver_path = r'D:\python\chromedriver.exe'
driver = webdriver.Chrome(executable_path=driver_path)
driver.get('https://mp.weixin.qq.com/')
time.sleep(2)
# 網(wǎng)頁(yè)最大化
driver.maximize_window()
# 拿微信掃描登錄
time.sleep(20)
# 獲得登錄的cookies
cookies_list = driver.get_cookies()
# 轉化成能用的cookie格式
cookie = [item["name"] + "=" + item["value"] for item in cookies_list]
cookie_str = '; '.join(item for item in cookie)
# 請求頭
headers_1 = {
'cookie': cookie_str,
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/91.0.4472.77 Safari/537.36'
}
# 起始地址
start_url = 'https://mp.weixin.qq.com/'
response = session.get(start_url, headers=headers_1).content.decode()
# 拿到token值,token值是有時(shí)效性的
token = re.findall(r'token=(\d+)', response)[0]
# 搜索出所有跟輸入的公眾號有關(guān)的
next_url = f'https://mp.weixin.qq.com/cgi-bin/searchbiz?action=search_biz&begin=0&count=5&query={user_name}&token=' \
f'{token}&lang=zh_CN&f=json&ajax=1'
# 獲取響應
response_1 = session.get(next_url, headers=headers_1).content.decode()
# 拿到fakeid的值,確定公眾號,唯一的
fakeid = re.findall(r'"fakeid":"(.*?)",', response_1)[0]
# 構造公眾號的url地址
next_url_2 = 'https://mp.weixin.qq.com/cgi-bin/appmsg?'
data = {
'action': 'list_ex',
'begin': '0',
'count': '5',
'fakeid': fakeid,
'type': '9',
'query': '',
'token': token,
'lang': 'zh_CN',
'f': 'json',
'ajax': '1'
}
headers_2 = {
'cookie': cookie_str,
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/91.0.4472.77 Safari/537.36',
'referer': f'https://mp.weixin.qq.com/cgi-bin/appmsgtemplate?action=edit&lang=zh_CN&token={token}',
'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
'sec-ch-ua-mobile': '?0',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'x-requested-with': 'XMLHttpRequest'
}
# 表的創(chuàng )建
workbook = xlwt.Workbook(encoding='gbk', style_compression=0)
sheet = workbook.add_sheet('test', cell_overwrite_ok=True)
j = 1
# 構造表頭
sheet.write(0, 0, '時(shí)間')
sheet.write(0, 1, '標題')
sheet.write(0, 2, '地址')
# 循環(huán)翻頁(yè)
for i in range(pass_wd):
data["begin"] = i * 5
time.sleep(3)
# 獲取響應的json數據
response_2 = session.get(next_url_2, params=data, headers=headers_2).json()
# jsonpath 獲取時(shí)間,標題,地址
title_list = jsonpath.jsonpath(response_2, '$..title')
url_list = jsonpath.jsonpath(response_2, '$..link')
create_time_list = jsonpath.jsonpath(response_2, '$..create_time')
# 將時(shí)間戳轉化為北京時(shí)間
list_1 = []
for create_time in create_time_list:
time_local = time.localtime(int(create_time))
time_1 = time.strftime("%Y-%m-%d", time_local)
time_2 = time.strftime("%H:%M:%S", time_local)
time_3 = time_1 + ' ' + time_2
list_1.append(time_3)
# for循環(huán)遍歷
for times, title, url in zip(list_1, title_list, url_list):
# 其中的'0-行, 0-列'指定表中的單元
sheet.write(j, 0, times)
sheet.write(j, 1, title)
sheet.write(j, 2, url)
j = j + 1
# 窗口顯示進(jìn)程
self.text1.insert("insert", f'*****************第{i+1}頁(yè)爬取成功*****************')
time.sleep(2)
self.text1.insert("insert", '\n ')
self.text1.insert("insert", '\n ')
# 最后保存成功
workbook.save(f'{user_name}公眾號信息.xls')
print(f"*********{user_name}公眾號信息保存成功*********")
def parse_hit_click_2(self):
"""定義觸發(fā)事件2,刪除文本框中內容"""
self.entry_user.delete(0, "end")
self.entry_passwd.delete(0, "end")
self.text1.delete("1.0", "end")
def center(self):
"""創(chuàng )建窗口居中函數方法"""
ws = self.window.winfo_screenwidth()
hs = self.window.winfo_screenheight()
x = int((ws / 2) - (800 / 2))
y = int((hs / 2) - (600 / 2))
self.window.geometry('{}x{}+{}+{}'.format(800, 600, x, y))
def run_loop(self):
"""禁止修改窗體大小規格"""
self.window.resizable(False, False)
"""窗口居中"""
self.center()
"""窗口維持--持久化"""
self.window.mainloop()
if __name__ == '__main__':
g = GZHSpider()
g.run_loop()