今年五一放了四天假,很多人不再只是选择周边游,因为时间充裕,选择了稍微远一点的景区,甚至出国游。各个景点成了人山人海,拥挤的人群,甚至去卫生间都要排队半天,那一刻我突然有点理解灭霸的行为了。
今天通过分析去哪儿网部分城市门票售卖情况,简单的分析一下哪些景点比较受欢迎,等下次假期可以做个参考。
抓取数据
通过请求https://piao.qunar.com/ticket/list.htm?keyword=北京,获取北京地区热门景区信息,再通过BeautifulSoup去分析提取出我们需要的信息。
这里爬取了前4页的景点信息,每页有15个景点。因为去哪儿并没有什么反爬措施,所以直接请求就可以了。
这里随机选择了13个热门城市:北京、上海、成都、三亚、广州、重庆、深圳、西安、杭州、厦门、武汉、大连、苏州。
并将爬取的数据存到了MongoDB数据库 。
爬虫部分完整代码如下:
import requests from bs4 import BeautifulSoup from pymongo import MongoClient class QuNaEr(): def __init__(self, keyword, page=1): self.keyword = keyword self.page = page def qne_spider(self): url = 'https://piao.qunar.com/ticket/list.htm?keyword=%s®ion=&from=mpl_search_suggest&page=%s' % (self.keyword, self.page) response = requests.get(url) response.encoding = 'utf-8' text = response.text bs_obj = BeautifulSoup(text, 'html.parser') arr = bs_obj.find('div', {'class': 'result_list'}).contents for i in arr: info = i.attrs # 景区名称 name = info.get('data-sight-name') # 地址 address = info.get('data-address') # 近期售票数 count = info.get('data-sale-count') # 经纬度 point = info.get('data-point') # 起始价格 price = i.find('span', {'class': 'sight_item_price'}) price = price.find_all('em') price = price[0].text conn = MongoClient('localhost', port=27017) db = conn.QuNaEr # 库 table = db.qunaer_51 # 表 table.insert_one({ 'name' : name, 'address' : address, 'count' : int(count), 'point' : point, 'price' : float(price), 'city' : self.keyword })