python使用webdriver爬取微信公众号
(编辑:jimmy 日期: 2025/11/3 浏览:3 次 )
本文实例为大家分享了python使用webdriver爬取微信公众号的具体代码,供大家参考,具体内容如下
# -*- coding: utf-8 -*-
from selenium import webdriver
import time
import json
import requests
import re
import random
#微信公众号账号
user=""
#公众号密码
password=""
#设置要爬取的公众号列表
gzlist=['香河微服务']
#登录微信公众号,获取登录之后的cookies信息,并保存到本地文本中
def weChat_login():
#定义一个空的字典,存放cookies内容
post={}
#用webdriver启动谷歌浏览器
print("启动浏览器,打开微信公众号登录界面")
driver = webdriver.Chrome(executable_path='E:\\program\\chromedriver.exe')
#打开微信公众号登录页面
driver.get('https://mp.weixin.qq.com/')
#等待5秒钟
time.sleep(5)
print("正在输入微信公众号登录账号和密码......")
#清空账号框中的内容
driver.find_element_by_xpath("//*[@id=\"header\"]/div[2]/div/div/form/div[1]/div[1]/div/span/input").clear()
#自动填入登录用户名
driver.find_element_by_xpath("//*[@id=\"header\"]/div[2]/div/div/form/div[1]/div[1]/div/span/input").send_keys(user)
#清空密码框中的内容
driver.find_element_by_xpath("//*[@id=\"header\"]/div[2]/div/div/form/div[1]/div[2]/div/span/input").clear()
#自动填入登录密码
driver.find_element_by_xpath("//*[@id=\"header\"]/div[2]/div/div/form/div[1]/div[2]/div/span/input").send_keys(password)
# 在自动输完密码之后需要手动点一下记住我
print("请在登录界面点击:记住账号")
time.sleep(10)
#自动点击登录按钮进行登录
driver.find_element_by_xpath("//*[@id=\"header\"]/div[2]/div/div/form/div[4]/a").click()
# 拿手机扫二维码!
print("请拿手机扫码二维码登录公众号")
time.sleep(20)
print("登录成功")
#重新载入公众号登录页,登录之后会显示公众号后台首页,从这个返回内容中获取cookies信息
driver.get('https://mp.weixin.qq.com/')
#获取cookies
cookie_items = driver.get_cookies()
#获取到的cookies是列表形式,将cookies转成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信息已保存到本地")
#爬取微信公众号文章,并存在本地文本中
def get_content(query):
#query为要爬取的公众号名称
#公众号主页
url = 'https://mp.weixin.qq.com'
#设置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)
#登录之后的微信公众号首页url变化为:https://mp.weixin.qq.com/cgi-bin/home":\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:
#登录微信公众号,获取登录之后的cookies信息,并保存到本地文本中
weChat_login()
#登录之后,通过微信公众号后台提供的微信公众号文章接口爬取文章
for query in gzlist:
#爬取微信公众号文章,并存在本地文本中
print("开始爬取公众号:"+query)
get_content(query)
print("爬取完成")
except Exception as e:
print(str(e))
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇:Python wxPython库消息对话框MessageDialog用法示例