我的任务是数据应用场景语料库的构建,后续会根据搜集的数据应用场景进行数据产品盈利预测。主要利用技术手段,包括爬虫、AI算法等实现这些功能。本文详细讲述我是如何爬取微信公众号合法合规有利信息的以及进行NLP分析并最终建立语料库的过程。持续更新
2024年12月9日方法(成功)
微信爬虫阶段的任务完成,后续建立AI大模型进行爬取,见此链接
通过搜狗微信和微信公众平台爬取微信公众号名称、标题、文章链接、文章全部文字内容,并通过IP池、代理池、打码平台、设置请求频率等处理爬取中断的情况-CSDN博客
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)}")