用py写一段爬取网页评论
以下是一个用Python爬取网页评论的示例:
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com/comments' # 替换为目标网页的评论页面链接
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
comments = soup.find_all('div', {'class': 'comment'}) # 替换为目标网页的评论区域的div类名
for comment in comments:
username = comment.find('span', {'class': 'username'}).text # 替换为目标网页的评论者用户名的span类名
content = comment.find('div', {'class': 'content'}).text # 替换为目标网页的评论内容的div类名
print('Username:', username)
print('Comment:', content)
print('---')
以上示例中,我们使用了Python的requests库来获取目标网页的HTML内容,并使用BeautifulSoup库来解析HTML。我们通过find_all()方法来获取所有评论的div元素,然后使用find()方法来获取每个评论的用户名和内容。最后,我们将结果打印到控制台中。在实际应用中,你可能需要将结果保存到文件或数据库中。
原文地址: https://www.cveoy.top/t/topic/boZz 著作权归作者所有。请勿转载和采集!