上一篇
如何高效获取文章评论数量,探索代码实现方法
- 行业动态
- 2024-09-29
- 2
“
python,import requests,,url = "文章链接",response = requests.get(url),comments = response.json()["comments"],print(len(comments)),
“
import requests from bs4 import BeautifulSoup def get_comment_count(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') comment_count = soup.find('div', {'class': 'commentscount'}).text return int(comment_count.replace(',', '')) url = 'https://example.com/article' comment_count = get_comment_count(url) print("评论个数:", comment_count)
在这段代码中,我们首先导入了requests
和BeautifulSoup
库,然后定义了一个名为get_comment_count
的函数,该函数接受一个URL参数,在函数内部,我们使用requests.get()
方法获取网页内容,然后使用BeautifulSoup
解析HTML,我们找到包含评论个数的<div>
标签,并提取其中的文本,我们将文本中的逗号去掉,并将其转换为整数。
在主程序中,我们调用get_comment_count
函数,传入文章的URL,并将返回的评论个数打印出来。