【发布时间】:2021-07-17 14:40:53
【问题描述】:
我想刮掉这个 reddit 页面中的所有 cmets,然后将数据写入 csv 文件。我已经写了这段代码。
我注意到所有 cmets 都是具有“RichTextJSON-root”类的“div”元素。
代码编写:
from bs4 import BeautifulSoup
import requests
import csv
# Reddit
source = requests.get(
'https://www.reddit.com/r/sysadmin/comments/gjkqvj/who_has_made_the_switch_from_dell_to_lenovo/').text
soup = BeautifulSoup(source, 'html.parser')
countreddit = 0
csv_file = open('reddit_scrape.csv', 'w')
writer = csv.writer(csv_file)
writer.writerow(['Comment'])
comments = soup.find_all('div', class_='RichTextJSON-root')
for comment in comments:
for para in comment.find_all('p'):
paratext = para.text
writer.writerow([paratext])
countreddit += 1
print(f'Reddit Count: {countreddit}')
csv_file.close()
reddit 帖子链接:https://www.reddit.com/r/sysadmin/comments/gjkqvj/who_has_made_the_switch_from_dell_to_lenovo/
但是,我只设法刮到网页的中间,停在评论“那些使用 WD15 扩展坞的人想和你谈谈”。请问如何才能刮到本页末尾?
我在其他帖子上读到可能是因为beautifulsoup抓取时,它只抓取网页上呈现的内容,此时网页尚未完全呈现。
谢谢!
【问题讨论】:
-
请发布您的代码而不是图片。
-
你应该使用 Reddit API!
标签: python web-scraping beautifulsoup