使用beautifulsoup对Reddit进行Web抓取嵌套评论

2024-03-29 01:43:06 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码获取页面。我的问题是我需要刮用户评论的内容而不是评论的数量。它嵌套在“评论数”部分中,但我不确定如何访问链接、解析和获取用户注释。在

request_list = []
id_list = [0]

for i in range(0,200,25): 
    response = requests.get("https://www.reddit.com/r/CryptoCurrency/?count="+str(i)+"&after="+str(id_list[-1]), headers = {'User-agent':'No Bot'})  
    soup = BeautifulSoup(response.content, 'lxml') 
    request_list.append(soup)
    id_list.append(soup.find_all('div', attrs={'data-type': 'link'})[-1]['data-fullname'])
    print(i, id_list)
    if i%100 == 0: 
        time.sleep(1)

下面的代码我试图编写一个函数,它应该访问嵌套的注释,但我没有线索。在

^{pr2}$

Tags: 代码用户id内容data数量链接response
1条回答
网友
1楼 · 发布于 2024-03-29 01:43:06

对于每个线程,您需要发送另一个请求来获取评论页面。可以使用soup.find_all('a', class_='bylink comments may-blank')找到评论页的url。这将为评论页提供所有的a标记的url。我将向您展示一个进入评论页面的示例。在

r = requests.get('https://www.reddit.com/r/CryptoCurrency/?count=0&after=0')
soup = BeautifulSoup(r.text, 'lxml')

for comments_tag in soup.find_all('a', class_='bylink comments may-blank', href=True):
    url = comments_tag['href']
    r2 = requests.get(url)
    soup = BeautifulSoup(r2.text, 'lxml')
    # Your job is to parse this soup object and get all the comments.

相关问题 更多 >