爬取微信公众号发布的所有文章构成语料库(包括文章,阅读数,在看数,点赞数等)

我的任务是数据应用场景语料库的构建,后续会根据搜集的数据应用场景进行数据产品盈利预测。主要利用技术手段,包括爬虫、AI算法等实现这些功能。本文详细讲述我是如何爬取微信公众号合法合规有利信息的。持续更新

2024年9月12日方法 (成功)

文章抓取→nlp分析→整理→抓最新的添加,

2024年9月11日方法 (成功)

# 成功爬取微信公众号文章。在sougou 微信网页版中,以“数据资产应用场景”为关键词搜索的5748篇文章对应的的链接、标题、发布时间并形成表格。
import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import pandas as pd
import time

# 配置Selenium,使用Chrome浏览器
options = webdriver.ChromeOptions()
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')

# 创建 ChromeDriver 服务
service = Service(r'D:\Desktop\chormedriver\chromedriver-win64\chromedriver.exe')  # 替换为你自己的chromedriver路径

# 启动 Chrome 浏览器
driver = webdriver.Chrome(service=service, options=options)

# 搜索的关键字
keyword = '数据应用场景'

# 搜狗微信搜索的URL模板
base_url = 'https://weixin.sogou.com/weixin?type=2&query={}&page={}'
max_pages = 2  # 假设最多翻100页,实际需要调整
results = []

def get_real_url(redirect_url):
    """
    通过重定向获取实际文章的URL
    """
    try:
        response = requests.get('https://weixin.sogou.com' + redirect_url, allow_redirects=True)
        return response.url
    except requests.exceptions.RequestException as e:
        print(f"Error getting real URL: {e}")
        return None

def get_articles_from_page(url):
    # 使用Selenium加载页面
    driver.get(url)

    # 显式等待,直到文章列表元素加载出来(最多等待10秒)
    try:
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "div.txt-box"))
        )
    except Exception as e:
        print(f"Error loading page: {e}")
        return []

    # 获取页面内容
    page_source = driver.page_source
    soup = BeautifulSoup(page_source, 'html.parser')

    # 查找文章列表容器
    articles = soup.find_all('div', class_='txt-box')

    if not articles:
        print("No articles found on this page.")

    print(f"Found {len(articles)} articles")

    article_list = []
    for article in articles:
        try:
            # 提取文章标题
            title_tag = article.find('a')
            title = title_tag.get_text() if title_tag else 'N/A'

            # 提取文章链接
            link = title_tag['href'] if title_tag else 'N/A'

            # 提取公众号名称
            account_tag = article.find('a', class_='account')
            account_name = account_tag.get_text() if account_tag else 'N/A'

            # 提取发布时间
            pub_time_tag = article.find('span', class_='s2')
            pub_time = pub_time_tag.get_text() if pub_time_tag else 'N/A'

            # 获取文章的真实URL
            real_url = get_real_url(link) if link != 'N/A' else 'N/A'

            # 将数据加入列表
            article_list.append({
                'title': title,
                'url': link,
                'account_name': account_name,
                'pub_time': pub_time,
                'real_url': real_url
            })
        except Exception as e:
            print(f"Error parsing article: {e}")
            continue
    return article_list


# 循环翻页抓取数据
for page in range(1, max_pages + 1):
    print(f"Scraping page {page}...")
    search_url = base_url.format(keyword, page)
    articles = get_articles_from_page(search_url)

    # 增加更多等待时间以处理人机验证问题
    time.sleep(10)  # 可以手动解决验证码

    if not articles:
        print("No more articles found or an error occurred.")
        break
    results.extend(articles)
    time.sleep(2)  # 爬取间隔,避免被封禁

# 保存结果为CSV文件
df = pd.DataFrame(results)
print("Saving CSV file...")
df.to_csv('weixin_articles.csv', index=False, encoding='utf-8-sig')
print("CSV file saved successfully.")

# 关闭浏览器
driver.quit()

print(f"Scraping completed. Total articles: {len(results)}")

23年9月14日的方法

标题:探索无限可能:微信公众号文章爬虫项目详解与应用推荐-CSDN博客

GitCode - 全球开发者的开源社区,开源代码托管平台

  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值