Python爬虫如何爬取搜狗微信公众号某关键词下的最新文章

http://weixin.sogou.com/weixin?type=2&ie=utf8&query=python&tsn=1&ft=&et=&interation=&wxid=&usip=
像这样的地址,总是被重定向到首页,但是浏览器里点时间线 一天内 是没有问题的,想问一下,有什么好的解决办法么?
Python爬虫如何爬取搜狗微信公众号某关键词下的最新文章


8 回复

要爬取搜狗微信的最新文章,你得先搞定搜狗的反爬机制。核心思路是模拟浏览器请求,解析返回的JSON数据。下面是一个可直接运行的示例,它处理了基础的请求头、参数和JSON解析。

import requests
import json
import time
from urllib.parse import quote

def fetch_sogou_wechat_articles(keyword, page=1):
    """
    爬取搜狗微信搜索中指定关键词的文章
    :param keyword: 搜索关键词
    :param page: 页码(从1开始)
    :return: 文章列表,每个元素是包含标题、摘要、链接等信息的字典
    """
    # 编码关键词
    encoded_keyword = quote(keyword)
    url = f"https://weixin.sogou.com/weixin"
    
    # 关键参数
    params = {
        'type': '2',  # 2表示搜索公众号文章
        'query': encoded_keyword,
        'ie': 'utf8',
        'page': page
    }
    
    # 请求头,模拟浏览器
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Referer': 'https://weixin.sogou.com/',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
    }
    
    # 发送请求
    try:
        response = requests.get(url, params=params, headers=headers, timeout=10)
        response.raise_for_status()  # 检查请求是否成功
        response.encoding = 'utf-8'
        html_content = response.text
    except requests.RequestException as e:
        print(f"请求失败: {e}")
        return []
    
    # 搜狗微信的搜索结果页中,文章数据在一个名为 `article` 的JSON对象里
    # 这里需要根据实际页面结构解析,以下为示例解析逻辑
    articles = []
    # 示例:假设文章信息在 class="news-list" 的 div 中
    # 实际解析时,你可能需要使用 BeautifulSoup 或正则表达式
    # 这里仅作示例,实际结构请以页面为准
    # 例如:使用 BeautifulSoup 解析
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html_content, 'html.parser')
    news_items = soup.find_all('div', class_='news-list')
    
    for item in news_items:
        try:
            title_tag = item.find('h3').find('a')
            title = title_tag.get_text(strip=True)
            link = title_tag['href']
            # 处理相对链接
            if link.startswith('/'):
                link = 'https://weixin.sogou.com' + link
            summary_tag = item.find('p', class_='txt-info')
            summary = summary_tag.get_text(strip=True) if summary_tag else ''
            # 获取公众号名称
            account_tag = item.find('a', class_='account')
            account = account_tag.get_text(strip=True) if account_tag else ''
            # 获取发布时间
            time_tag = item.find('span', class_='s2')
            pub_time = time_tag.get_text(strip=True) if time_tag else ''
            
            articles.append({
                'title': title,
                'link': link,
                'summary': summary,
                'account': account,
                'pub_time': pub_time
            })
        except AttributeError as e:
            # 如果某个元素找不到,跳过该项
            continue
    
    return articles

# 使用示例
if __name__ == "__main__":
    keyword = "Python编程"
    articles = fetch_sogou_wechat_articles(keyword, page=1)
    for idx, article in enumerate(articles, 1):
        print(f"{idx}. 标题: {article['title']}")
        print(f"   链接: {article['link']}")
        print(f"   摘要: {article['summary']}")
        print(f"   公众号: {article['account']}")
        print(f"   时间: {article['pub_time']}")
        print("-" * 50)
    print(f"共获取到 {len(articles)} 篇文章")

关键点说明:

  1. 请求参数type=2 表示搜索文章,query 是编码后的关键词,page 控制页码。
  2. 请求头:必须设置 User-AgentReferer,否则容易被封。
  3. 解析:示例用了 BeautifulSoup,但搜狗页面结构可能变化,你需要检查实际HTML并调整选择器。
  4. 反爬:搜狗有频率限制,连续请求需加 time.sleep() 避免IP被封。更严格的可能需要处理Cookie或验证码。

一句话建议:直接模拟请求并解析JSON是最快的方法,但要注意反爬策略。

这个访问是没问题不过这个不带时间节点呀~希望是选择 时间为 一天内的文章,然后就会被重定向

pip install wechatsogou

这个我装了 不过似乎也不能根据关键词抓取哦

确实可以了哈,非常感谢

回到顶部