Python爬虫第一练,爬取13个旅游城市游客数据

492 阅读2分钟

1.需要用到的Python模块:

BeautifulSoup、requests、pymongo、pylab

2.方法:

通过请求piao.qunar.com/ticket/list…北京,获取北京地区人们景点景区信息,再通过BeautifulSoup去分析提取我们需要的信息
目前只爬取了前4页的景点信息,每页有15个景点。
(该程序所查找的网页无反爬措施,直接请求可以进入)
这里随机选取13个热门城市:北京,上海,广州,深圳,武汉,成都,三亚,重庆,西安,杭州,厦门,大连,苏州。所爬取数据保存到了MongoDB数据库

爬虫部分完整代码如下:

import requests
from bs4 import BeautifulSoup
from pymongo import MongClient
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&region&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'  :  folat(price)
    'city'    :   self.keyword
    })
    if_name_=='_main_':
    city=['北京','上海','广州','深圳','武汉','成都','三亚','重庆','西安','杭州','厦门','大连','苏州']
    for i in city:
       for page in range(1,5):
       #这里的5可以换成任何数
       qne=QuNaEr(i,page=page)
       qne.qne_spider()

有数据就能分析出我们想要的东西

最受欢迎的15个景区:
代码如下:

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.xlable(u'景点名称')  #x轴描叙信息
plt.ylable(u'月销量')  #y轴描叙信息
plt.title(u,'景点销售统计表')  #指定图表描叙信息
plt.ylim(0,4000)   #指定Y轴的高度
plt.savefig('去哪儿月销量排行榜')   #保存为图片
plt.show()

对python感兴趣的可加QQ:3145679695一起学习交流分享