1.通过请求https://piao.qunar.com/ticket/list.htm?keyword=北京 ,获取北京地区热门景区信息,再通过BeautifulSoup去分析提取出我们需要的信息。
2.这里为了偷懒只爬取了前4页的景点信息,每页有15个景点。因为去哪儿并没有什么反爬措施,所以直接请求就可以了。
3.这里只是随机选择了13个热门城市:北京, 上海, 成都, 三亚, 广州, 重庆, 深圳, 西安, 杭州, 厦门, 武汉, 大连, 苏州。
4.并将爬取的数据存到了MongoDB数据库 。import requests from bs4 import BeautifulSoup from pymongo import MongoClient // 堆代码 duidaima.com 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 }) if __name__ == '__main__': citys = ['北京', '上海', '成都', '三亚', '广州', '重庆', '深圳', '西安', '杭州', '厦门', '武汉', '大连', '苏州'] for i in citys: for page in range(1, 5): qne = QuNaEr(i, page=page) qne.qne_spider()效果图如下
from pymongo import MongoClient # 设置字体,不然无法显示中文 from pylab import * mpl.rcParams['font.sans-serif'] = ['SimHei'] conn = MongoClient('localhost', port=27017) db = conn.QuNaEr # 库 table = db.qunaer_51 # 表 result = table.find().sort([('count', -1)]).limit(15) # x,y轴数据 x_arr = [] # 景区名称 y_arr = [] # 销量 for i in result: x_arr.append(i['name']) y_arr.append(i['count']) """ 去哪儿月销量排行榜 """ plt.bar(x_arr, y_arr, color='rgb') # 指定color,不然所有的柱体都会是一个颜色 plt.gcf().autofmt_xdate() # 旋转x轴,避免重叠 plt.xlabel(u'景点名称') # x轴描述信息 plt.ylabel(u'月销量') # y轴描述信息 plt.title(u'拉钩景点月销量统计表') # 指定图表描述信息 plt.ylim(0, 4000) # 指定Y轴的高度 plt.savefig('去哪儿月销售量排行榜') # 保存为图片 plt.show()