python爬虫评论实践源码
时间: 2023-10-14 18:05:09 浏览: 46
当然,下面是一个简单的示例爬虫评论实践的Python源码:
```python
import requests
from bs4 import BeautifulSoup
def scrape_comments(url):
# 发送GET请求获取页面内容
response = requests.get(url)
# 解析HTML页面
soup = BeautifulSoup(response.text, 'html.parser')
# 找到评论的元素,根据实际页面结构进行修改
comments = soup.find_all('div', class_='comment')
# 提取评论文本并打印
for comment in comments:
text = comment.find('p').text.strip()
print(text)
print('-' * 50)
if __name__ == '__main__':
url = 'https://example.com/comments' # 替换为目标页面的URL
scrape_comments(url)
```
以上代码使用了`requests`库发送GET请求,使用`BeautifulSoup`库解析HTML页面。你需要根据目标网页的实际结构,修改代码中的选择器,例如`find_all('div', class_='comment')`这一行。
请注意,爬虫涉及到抓取网页内容,需要遵守网站的使用规范和法律法规,并尊重网站的隐私政策。在实际使用中,请确保你有合法的授权和充分理解相关法律要求。