使用BeautifulSoup从Reddit页面抓取评论的时间戳数据未返回任何结果
我正在尝试抓取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()
当我查看评论的时间戳时,发现它们都有一个相同的类名“3yx4Dn0W3Yunucf5sVJeFU”,这个类名在属性“a”下。所以,我试着直接提取这个类的时间戳文本。但是没有返回任何内容,这让我很困惑。我也尝试过使用lxml,但也没有成功。
另外,Reddit在你将鼠标悬停在时间戳文本上时,会显示精确到秒的时间。我将来可能想抓取这些数据,但现在我只是想抓取评论上的普通时间戳文本。
1 个回答
0
我是楼主。目前我找到了一个离线的解决办法。一旦我在浏览器上安装了JSONvue,看到JSON数据的结构后,我就很清楚怎么获取我想要的时间戳了。请原谅我的方法有些不够高效,因为时间戳数据的层次结构比较复杂。
另外,很明显,通过在网址后面加上.json并不能获取到帖子中每一条主要评论的数据,因为这些数据可能是通过JavaScript动态加载的,正如有人提到的那样。我也尝试过直接从网址请求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)
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