使用 BeautifulSoup 从 Reddit 页面上抓取评论的时间戳数据不会返回任何内容

问题描述 投票:0回答:1

出于研究目的,我正在尝试抓取 Reddit 线程中所有评论的时间戳。截至目前,该帖子共有约 700 条评论。因此,我认为在不使用现有应用程序或扩展的情况下抓取这些数据的最佳方法是通过 SOUP。下面是我为此编写的 python 程序的开始部分。

from bs4 import BeautifulSoup
import requests
import csv

url = "https://www.reddit.com/r/NewTubers/comments/1bfhcwz/feedback_friday_post_your_videos_here_if_you_want/"
r = requests.get(url)
#print(r.status_code) returned 200

soup = BeautifulSoup(r.content, 'html.parser') #lxml didn't work either
#print(soup.title) returned the correct title of the HTML page
file = open("scraped_timestamps.csv", "w")
writer = csv.writer(file)
writer.writerow(["TIMESTAMPS"])

timestamps = soup.findAll('a', class_='_3yx4Dn0W3Yunucf5sVJeFU')
for timestamp in timestamps:
    writer.writerow([timestamp.text])
file.close()

当检查评论的时间戳时,它们在属性“a”下都有一个相同的类“3yx4Dn0W3Yunucf5sVJeFU”。因此,针对这个确切的类,我尝试打印出时间戳文本。这没有返回任何东西,所以我很困惑。我尝试过使用 lxml 但我也没有工作。

此外,当您将鼠标悬停在时间戳文本上时,Reddit 会显示精确到秒的准确时间。我希望将来也可以抓取这些数据,但现在我只是想抓取评论上的通用时间戳文本。

python html beautifulsoup request reddit
1个回答
0
投票

我现在已经找到了离线解决方案。当我在浏览器上安装 JSONvue 并看到 JSON 数据的结构后,如何获取我想要的时间戳就变得非常清楚了。请原谅任何效率低下的情况,因为时间戳数据非常嵌套。

很明显,通过在 url 末尾放置 .json 来检索 JSON 并没有给我帖子中每条主要评论的数据,因为正如有人指出的那样,它可能是由 Javascript 动态加载的。我尝试过从 URL 本身请求 HTML 和 json,但有一半的时间会失败,并返回与我当前代码不兼容的数据结构。然而,无论哪种情况,这些数据似乎仍然只是现有数据的一小部分。我将进一步探索这个练习,如何获取所有评论的数据

这是代码:

#from bs4 import BeautifulSoup
#import requests
import json
import csv
import datetime

data = open('Reddit.json')
html_json = json.load(data)
file = open("scraped_timestamps.csv", "w")
writer = csv.writer(file)
writer.writerow(["TIMESTAMPS"])
#print(html.status_code)

file = open("scraped_timestamps.csv", "w")
writer = csv.writer(file)
writer.writerow(["TIMESTAMPS"])

parent = html_json[1]['data']['children']
timestamps = []

for i in parent:
    if 'created_utc' in i['data']:
        timestamps.append(datetime.datetime.fromtimestamp(i['data]['created_utc']))
    else:
        break

sorted_timestamps = sorted(timestamps)
for x in sorted_timestamps:
    writer.writerow([x])
file.close()

#html_json[0] contains the post itself without the comment section
#html_json[1] contains the entire comment section
#I had to check for the existence of the timestamp data, otherwise the query throws
#an error passing the list as html_json[1] also contains the footer without such timestamp data
© www.soinside.com 2019 - 2024. All rights reserved.