Reddit爬取异常:投票、发布者等数据重复问题求助
解决Old Reddit r/wholesomememes板块爬取数据重复的问题
问题根源
你遇到的数据重复问题,核心原因是翻页参数没有正确更新:
- 循环中
after参数始终固定为t3_1axl8xu,导致每次请求拉取的都是从该标记点开始的同一批帖子 count参数的循环逻辑range(0,100,50)不符合Reddit分页规则,它应该对应已经加载的帖子总数,而非固定步进值
修复方案
要实现正确的分页爬取,需要:
- 每次爬取完一页后,提取该页最后一个帖子的
name属性(格式为t3_xxx),作为下一页请求的after参数 - 动态维护
count值,每次累加当前页获取到的帖子数量 - 可选:添加数据去重逻辑,作为兜底保障
修正后的代码
import requests from bs4 import BeautifulSoup import pandas as pd headers = { 'User-Agent': 'explore.whatismybrowser.com/useragents/parse/574433748-chrome-windows-blink' } # 初始化存储列表和分页参数 titles = [] votes = [] publishers = [] after = None count = 0 total_posts_to_scrape = 100 # 目标爬取总数量 while len(titles) < total_posts_to_scrape: # 构建请求URL,根据after参数决定是否添加分页标记 if after: url = f"https://old.reddit.com/r/wholesomememes/?count={count}&after={after}" else: url = f"https://old.reddit.com/r/wholesomememes/?count={count}" r = requests.get(url, headers=headers) soup = BeautifulSoup(r.content, 'lxml') posts = soup.find_all('div', class_='thing') # 如果没有获取到帖子,终止循环(避免无限请求) if not posts: break # 遍历当前页帖子 for post in posts: # 避免超过目标数量 if len(titles) >= total_posts_to_scrape: break # 获取标题 title_element = post.find('a', class_='title may-blank outbound') titles.append(title_element.text.strip() if title_element else "") # 获取投票数 votes_element = post.find('div', class_='score likes') votes.append(votes_element.text.strip() if votes_element else "") # 获取发布者 author_element = post.find('a', class_='author') publishers.append(author_element.text.strip() if author_element else "") # 更新分页参数:取最后一个帖子的name作为下一页的after after = posts[-1]['data-fullname'] # 更新count为已爬取的总帖子数 count += len(posts) # 转换为DataFrame并可选去重 data = { "title": titles, "author": publishers, "votes": votes } df = pd.DataFrame(data) # 基于标题和作者去重(兜底) df = df.drop_duplicates(subset=['title', 'author'], keep='first')
额外说明
- Reddit的
after参数必须是上一页最后一个帖子的唯一标识符(data-fullname属性值),才能正确加载下一页内容 - 添加
len(titles) >= total_posts_to_scrape判断,避免爬取超过目标数量的帖子 drop_duplicates作为兜底逻辑,即使分页参数出现小问题,也能确保最终数据无重复
内容的提问来源于stack exchange,提问作者Yahya Khalid
相关产品推荐
相关产品推荐

