Python微信公众号爬虫如何实现?

微信公众号这个网站的接口登陆 如何 获取 token 的 我要爬公众号 网上都说 selenium 的


Python微信公众号爬虫如何实现?
2 回复

要爬微信公众号文章,得用几个关键库配合。核心思路是通过搜狗微信搜索获取文章链接,再用requests和BeautifulSoup解析内容。

import requests
from bs4 import BeautifulSoup
import re
import time

class WechatCrawler:
    def __init__(self):
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
        self.base_url = 'https://weixin.sogou.com/weixin'
    
    def search_articles(self, keyword, page=1):
        """搜索公众号文章"""
        params = {
            'type': 2,
            'query': keyword,
            'page': page
        }
        
        try:
            response = requests.get(self.base_url, params=params, headers=self.headers)
            response.encoding = 'utf-8'
            soup = BeautifulSoup(response.text, 'html.parser')
            
            articles = []
            for item in soup.find_all('div', class_='txt-box'):
                title_tag = item.find('h3')
                if title_tag and title_tag.a:
                    title = title_tag.a.text.strip()
                    link = title_tag.a['href']
                    summary = item.find('p', class_='txt-info').text.strip() if item.find('p', class_='txt-info') else ''
                    
                    # 处理相对链接
                    if link.startswith('/'):
                        link = 'https://weixin.sogou.com' + link
                    
                    articles.append({
                        'title': title,
                        'link': link,
                        'summary': summary
                    })
            
            return articles
            
        except Exception as e:
            print(f"搜索失败: {e}")
            return []
    
    def get_article_content(self, url):
        """获取文章详细内容"""
        try:
            # 先访问搜狗链接获取真实文章链接
            response = requests.get(url, headers=self.headers, allow_redirects=False)
            
            # 提取真实文章链接
            if 'Location' in response.headers:
                real_url = response.headers['Location']
                # 访问真实文章页面
                article_response = requests.get(real_url, headers=self.headers)
                article_response.encoding = 'utf-8'
                
                soup = BeautifulSoup(article_response.text, 'html.parser')
                
                # 提取文章内容
                content_div = soup.find('div', id='js_content')
                if content_div:
                    # 清理不需要的元素
                    for script in content_div.find_all('script'):
                        script.decompose()
                    for style in content_div.find_all('style'):
                        style.decompose()
                    
                    content = content_div.get_text(strip=True, separator='\n')
                    return content
                
            return None
            
        except Exception as e:
            print(f"获取内容失败: {e}")
            return None
    
    def crawl(self, keyword, max_pages=3):
        """主爬取函数"""
        all_articles = []
        
        for page in range(1, max_pages + 1):
            print(f"正在爬取第 {page} 页...")
            articles = self.search_articles(keyword, page)
            
            for article in articles:
                print(f"处理文章: {article['title']}")
                content = self.get_article_content(article['link'])
                if content:
                    article['content'] = content
                    all_articles.append(article)
                
                time.sleep(2)  # 礼貌性延迟
            
            time.sleep(3)
        
        return all_articles

# 使用示例
if __name__ == "__main__":
    crawler = WechatCrawler()
    
    # 搜索"Python"相关的文章
    results = crawler.crawl("Python", max_pages=2)
    
    # 输出结果
    for i, article in enumerate(results, 1):
        print(f"\n{i}. {article['title']}")
        print(f"链接: {article['link']}")
        print(f"摘要: {article.get('summary', '')[:100]}...")
        print(f"内容预览: {article.get('content', '')[:200]}...")

这个爬虫有几个要点:1)用搜狗微信搜索作为入口,因为直接访问微信需要登录;2)处理重定向获取真实文章链接;3)添加适当的延迟避免被封;4)清理HTML标签提取纯文本。

注意微信的反爬机制比较严格,可能需要处理验证码或使用代理IP。另外,搜索结果可能不完整,有些公众号设置了访问限制。

总结:用搜狗微信搜索做入口,处理好重定向和反爬就行。


回到顶部