6.8 KiB
title, author, url, created, voteup, comments, platform, type
| title | author | url | created | voteup | comments | platform | type |
|---|---|---|---|---|---|---|---|
| 如何高效的爬取微信公众号 | null | https://zhuanlan.zhihu.com/p/1894054073625461813 | 2025-04-11 16:08:57 | 0 | 0 | zhihu | article |
如何高效的爬取微信公众号
作者: null
来源: 知乎专栏
发布时间: 2025-04-11 16:08:57
点赞: 0
评论: 0
⚠️ 免责声明本文仅为个人学习与技术研究用途,所涉及的爬虫程序用于探索公开网页的数据结构及自动化处理方式。采集的数据未被用于任何商业用途,也不涉及敏感或受限信息的抓取。如有侵犯任何平台的相关规定或权益,请及时联系本人删除。 以下内容旨在分享爬虫开发中的经验与技术细节,希望对同样热爱技术的你有所启发。 前提知识熟悉一门编程语言(如 Python / Java / Golang 等)了解基本网页结构(HTML / DOM)熟悉 Selenium 基本操作 ️ 微信公众号文章爬取说明❌ 过去的方式:搜狗搜索接口(已失效)早期,我们可以通过 搜狗搜索接口 获取公众号文章数据,无需登录验证,非常方便。但随着平台策略变化,该方式已无法继续使用。✅ 当前方法:微信公众号后台接口爬取我们通过 微信公众号后台文章管理接口 来获取文章列表,实现爬取逻辑。该接口返回的是你关注或搜索到的公众号所发布的文章列表,其 URL 中包含两个关键参数:fakeid:表示公众号的唯一标识符。token:登录后平台发放的访问令牌。此外,接口请求还必须携带有效的登录 Cookie。⚠️ 注意事项:token 和 cookie 都具有时效性(大约有效期为 2~3 天)。一旦过期,爬虫程序将无法获取数据,必须重新登录。 解决方案:自动化登录为了确保爬虫长期稳定运行,我们采用 Selenium 自动扫码登录 的方式,获取登录后的 token 与 cookie。实现逻辑如下:启动浏览器,访问微信公众号后台。扫码登录后,从浏览器请求中提取 token 和 cookie。将有效信息保存到数据库中。爬虫启动时从数据库读取公众号列表及对应的文章接口地址。检查 token / cookie 是否过期,若失效,则自动触发重新扫码流程,刷新数据。我讲讲我目前的处理方式,首选数据库存储我要爬哪些公众号,将公众号名称存储下来,然后记录上图中的url,然后将token和cookie存储下来。遍历所有的公众号调用接口即可实现,如果token过期就采用自动化的方式更新token和cookie即可!伪代码如下,可以根据自己的业务进行更改。只提供思路。options = webdriver.ChromeOptions() driver = webdriver.Chrome(options=options) driver.get("https://mp.weixin.qq.com/") try: WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.CLASS_NAME, "login__type__container__scan__qrcode")) ) while True: current_url = driver.current_url if "token" in current_url: print("登录成功,检测到token 准备进行跳转") parsed_url = urlparse.urlparse(current_url) token = urlparse.parse_qs(parsed_url.query).get("token", [""])[0] timestamp = int(time.time() * 1000) new_url = ( f"https://mp.weixin.qq.com/cgi-bin/appmsg?" f"t=media/appmsg_edit_v2&action=edit&isNew=1&type=77&createType=0" f"&token={token}&lang=zh_CN×tamp={timestamp}" )
driver.get(new_url)
print(f"跳转到新页面: {new_url}")
WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, "js_editor_insertlink"))
).click()
print("已自动点击超链接")
# <button type="button" class="weui-desktop-btn weui-desktop-btn_default">选择其他公众号</button>
WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, ".weui-desktop-btn.weui-desktop-btn_default"))
).click()
print("已自动点击选择其他公众号")
input_box = WebDriverWait(driver, 50).until(
EC.visibility_of_element_located(
(By.XPATH,
"//input[@class='weui-desktop-form__input' and @placeholder='输入文章来源的账号名称或微信号,回车进行搜索']"))
)
print("已自动键入北京")
input_box.send_keys("北京")
search_button = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, ".weui-desktop-icon.weui-desktop-icon__search"))
)
driver.execute_script("arguments[0].click();", search_button)
print("已自动点击搜索")
WebDriverWait(driver, 10).until(
lambda driver: any("searchbiz" in request.url for request in driver.requests)
)
for request in driver.requests:
if "searchbiz" in request.url:
cookie = request.headers.get("Cookie")
cookie = [cookie.strip() for cookie in cookie.split(';') if cookie]
cookie_dict = {item.split('=')[0]: item.split('=')[1] for item in cookie}
formatted_cookies = ',\n'.join([f'"{key}": "{value}"' for key, value in cookie_dict.items()])
new_cookie = "{" + formatted_cookies + "}"
conn = db_factory.get_conn()
cur = conn.cursor()
cur.execute(update_property_sql, (new_cookie, 'vx_cookie'))
cur.execute(update_property_sql, (token, 'vx_token'))
cur.execute(update_property_sql, (1, 'vx_available'))
conn.commit()
wx_spy_manager = WxSpyManager()
wx_spy_manager.get_more_data()
break
print("自动化爬虫完毕")
break
time.sleep(1) # 每秒检查一次✅ 小结本方案基于微信公众号后台接口,实现了较为稳定的自动化文章爬取功能。通过 Selenium 自动化登录,可以解决传统接口过期失效的问题,为数据采集提供便利。后续文章将介绍爬虫核心模块的设计、异常处理、并发优化等更多实践内容。欢迎持续关注!