用Python一键爬取艺龙酒店各个城市数据存入mysql
- 前言:
在这篇文章中,我将分享如何利用Python轻松爬取易龙API中的酒店数据。易龙是一家知名的中国酒店预订平台,他们的API提供了丰富的酒店信息,包括价格、评论等。我们将使用Python以及Requests库进行HTTP请求,BeautifulSoup库用于解析HTML。
- 准备工作:
Python基础知识
HTTP请求和API的基本了解
在你的系统上安装Python
安装Requests库 (pip install requests)
脚本编写:
首先,让我们设置Python环境。创建一个新的Python文件(例如 yilong_scraper.py)并导入必要的库:
import json
import time
import requests
抓取酒店数据:
现在,让我们深入代码。我们首先定义一个名为 YiLongList 的类来处理抓取过程。这个类将有方法来从API获取酒店数据和解析JSON响应。
class YiLongList:
def __init__(self, inDate, outDate, city):
# 初始化类变量
self.inDate, self.outDate = inDate, outDate
self.city = city
self.session = requests.Session()
self.hotels_data = []
def jxList(self, hotelList):
# 从酒店列表中提取数据的方法
for h in hotelList:
# 从每个酒店中提取相关信息
hotelName = h.get("hotelName")
starLevelDes = h.get("starLevelDes")
commentScore = h.get("commentScore")
# 以此类推提取其他字段
# 构建一个包含提取数据的字典
data = {
'hotelName': hotelName,
'starLevelDes': starLevelDes,
'commentScore': commentScore,
# 类似地添加其他字段
}
# 将数据添加到列表中
self.hotels_data.append(data)
# 打印提取的数据(可选)
print(hotelName, starLevelDes, commentScore)
def getList(self, page, traceToken):
url = "https://hotel.elong.com/tapi/v2/list"
if page == 0:
params = {