携程酒店数据爬取青城山
时间: 2023-12-22 12:27:00 浏览: 169
以下是携程酒店数据爬取青城山的Python代码示例:
```python
import requests
import json
import prettytable as pt
# 读取城市ID
with open('City.json', 'r', encoding='utf-8') as f:
city_json = json.load(f)
city_id = city_json['青城山']
# 构造请求URL
url = 'https://hotels.ctrip.com/Domestic/Tool/AjaxHotelList.aspx'
params = {
'city': city_id,
'page': 1
}
# 发送请求并解析数据
hotel_list = []
while True:
response = requests.get(url, params=params)
data = json.loads(response.text)
hotels = data['hotelList']
if not hotels:
break
for hotel in hotels:
hotel_list.append([
hotel['hotelName'],
hotel['positionArea'],
hotel['starName'],
hotel['price'],
hotel['score'],
hotel['commentCount']
])
params['page'] += 1
# 输出数据
table = pt.PrettyTable()
table.field_names = ['酒店名称', '位置', '星级', '价格', '评分', '评论数']
for hotel in hotel_list:
table.add_row(hotel)
print(table)
```
该代码使用requests模块向携程酒店数据接口发送请求,获取青城山地区的酒店数据,并使用prettytable模块将数据以表格形式输出。
阅读全文