Python爬取携程指定景点评论的用户、评论内容及时间

作者:暴富20212024.01.17 10:44浏览量:9

简介:本文将介绍如何使用Python爬取携程指定景点(以黄龙溪为例)的用户、评论内容及时间。我们将使用requests和BeautifulSoup库进行网页抓取,并使用pandas库进行数据处理。

千帆应用开发平台“智能体Pro”全新上线 限时免费体验

面向慢思考场景,支持低代码配置的方式创建“智能体Pro”应用

立即体验

首先,你需要安装requests和BeautifulSoup库,你可以使用以下命令进行安装:

  1. pip install requests beautifulsoup4

接下来,我们可以使用以下代码来爬取黄龙溪景点的用户、评论内容及时间:

  1. import requests
  2. from bs4 import BeautifulSoup
  3. import pandas as pd
  4. # 定义目标URL
  5. url = 'https://hotels.ctrip.com/hotel/list/review/hotelId=3885096.0&areaId=1000057&cityId=1000005&pageNo=1&pageSize=10&sort=0&order=0'
  6. # 发送HTTP请求并获取网页内容
  7. response = requests.get(url)
  8. soup = BeautifulSoup(response.text, 'html.parser')
  9. # 提取用户、评论内容及时间
  10. comments = soup.find_all('div', class_='hotel-list-review')
  11. user_list = []
  12. content_list = []
  13. time_list = []
  14. for comment in comments:
  15. user = comment.find('span', class_='review-user').text.strip()
  16. content = comment.find('p', class_='review-content').text.strip()
  17. time = comment.find('span', class_='review-time').text.strip()
  18. user_list.append(user)
  19. content_list.append(content)
  20. time_list.append(time)
  21. # 将数据保存为CSV文件
  22. df = pd.DataFrame({'User': user_list, 'Content': content_list, 'Time': time_list})
  23. df.to_csv('huanglongxi_comments.csv', index=False)

在上面的代码中,我们首先定义了目标URL,然后使用requests库发送HTTP请求并获取网页内容。接下来,我们使用BeautifulSoup库来解析网页内容,并提取用户、评论内容及时间。最后,我们将数据保存为CSV文件。
需要注意的是,由于网站的结构可能会发生变化,因此你需要定期检查和更新代码。此外,爬取网站数据需要遵守相关法律法规和网站的使用协议,确保你的行为合法合规。

article bottom image

相关文章推荐

发表评论