Python爬虫批量旅游景点信息数据并保存本地

作者:KAKAKA2024.01.18 00:54浏览量:11

简介:本文将介绍如何使用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. # 定义要爬取的网站列表
  5. websites = [
  6. 'http://example.com/destination1',
  7. 'http://example.com/destination2',
  8. 'http://example.com/destination3',
  9. # 添加更多旅游景点网站...
  10. ]
  11. # 定义要爬取的景点信息列表
  12. info_list = [
  13. '景点名称', '景点评分', '景点介绍', '门票价格', '开放时间', '地址', '联系方式'
  14. ]
  15. # 定义保存数据的文件名
  16. output_file = '旅游景点信息.csv'
  17. # 初始化一个空列表来保存景点信息
  18. info_dicts = []
  19. # 遍历网站列表,爬取每个旅游景点的信息
  20. for website in websites:
  21. try:
  22. response = requests.get(website)
  23. response.raise_for_status() # 如果请求返回的状态码不是200,则抛出异常
  24. soup = BeautifulSoup(response.text, 'html.parser')
  25. # 根据网站结构选择解析页面信息的标签,这里假设是div标签,标签的类名为info-item
  26. info_items = soup.select('div.info-item')
  27. for item in info_items:
  28. info_dict = {}
  29. for info in info_list:
  30. # 根据网站结构选择解析每个景点信息的标签,这里假设是span标签,标签的类名为info-item-value
  31. value = item.select('span.' + info)[0].text.strip() if item.select('span.' + info) else ''
  32. info_dict[info] = value
  33. info_dicts.append(info_dict)
  34. except requests.exceptions.RequestException as e:
  35. print(f'Failed to get information from {website}: {e}')
  36. continue
  37. except Exception as e:
  38. print(f'Failed to parse information from {website}: {e}')
  39. continue
  40. # 将景点信息保存到CSV文件中
  41. df = pd.DataFrame(info_dicts)
  42. df.to_csv(output_file, index=False)
  43. print(f'旅游景点信息已保存到 {output_file}')

以上代码会爬取每个旅游景点的名称、评分、介绍、门票价格、开放时间、地址和联系方式等信息,并将这些信息保存到CSV文件中。你可以根据需要修改代码来适应不同的网站结构和需要爬取的信息。请注意,在使用爬虫时,要遵守网站的robots协议和法律法规,不要频繁地访问网站,以免对网站的正常运行造成影响。

article bottom image

相关文章推荐

发表评论