Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析


Posted in Python onOctober 16, 2021

知识点

  • requests 发送网络请求
  • parsel 解析数据
  • csv 保存数据

第三方库

  • requests >>> pip install requests
  • parsel >>> pip install parsel

开发环境:

  • 版 本: python 3.8
  • 编辑器:pycharm 2021.2

Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析

【付费VIP完整版】只要看了就能学会的教程,80集Python基础入门视频教学

点这里即可免费在线观看

爬虫程序

导入模块

# 发送网络请求的模块
import requests
# 解析数据的模块
import parsel
import csv
import time
import random

发送请求

url = f'https://travel.qunar.com/travelbook/list.htm?page=1&order=hot_heat'
# <Response [200]>: 告诉我们 请求成功了
response = requests.get(url)

获取数据(网页源代码)

html_data = response.text

解析网页(re正则表达式,css选择器,xpath,bs4/六年没更新了,json)

# html_data: 字符串
# 我们现在要把这个字符串 变成一个对象
selector = parsel.Selector(html_data)
# ::attr(href) url_list:列表
url_list = selector.css('.b_strategy_list li h2 a::attr(href)').getall()
for detail_url in url_list:
    # 字符串的 替换方法
    detail_id = detail_url.replace('/youji/', '')
    url_1 = 'https://travel.qunar.com/travelbook/note/' + detail_id
    print(url_1)

向详情页网站发送请求(get,post)

# https://travel.qunar.com/travelbook/note/7701502
response_1 = requests.get(url_1).text

解析网页

selector_1 = parsel.Selector(response_1)
# :nth-child(): 伪类选择器
# ::text 提取文本内容
# * 代表所有
# 地点
title = selector_1.css('.b_crumb_cont *:nth-child(3)::text').get().replace('旅游攻略', '')
# 短评
comment = selector_1.css('.title.white::text').get()
# 出发日期
date = selector_1.css('#js_mainleft > div.b_foreword > ul > li.f_item.when > p > span.data::text').get()
# 天数
days = selector_1.css('#js_mainleft > div.b_foreword > ul > li.f_item.howlong > p > span.data::text').get()
# 人均消费
money = selector_1.css('#js_mainleft > div.b_foreword > ul > li.f_item.howmuch > p > span.data::text').get()
# 人物
character = selector_1.css('#js_mainleft > div.b_foreword > ul > li.f_item.who > p > span.data::text').get()
# 玩法
play_list = selector_1.css('#js_mainleft > div.b_foreword > ul > li.f_item.how > p > span.data span::text').getall()
play = ' '.join(play_list)
# 浏览量
count = selector_1.css('.view_count::text').get()
print(title, comment, date, days, money, character, play, count)

保存数据

# 保存成csv
csv_qne = open('去哪儿.csv', mode='a', encoding='utf-8', newline='')
csv_writer = csv.writer(csv_qne)
# 写入数据
csv_writer.writerow(['地点', '短评', '出发时间', '天数', '人均消费', '人物', '玩法', '浏览量'])

Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析

数据可视化

导入模块

import pandas as pd
from pyecharts.commons.utils import JsCode
from pyecharts.charts import *
from pyecharts import options as opts

导入数据

data = pd.read_csv('去哪儿_数分.csv')
data

Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析

旅游胜地Top10及对应费用

bar=(
    Bar(init_opts=opts.InitOpts(height='500px',width='1000px',theme='dark'))
    .add_xaxis(m2)
    .add_yaxis(
        '目的地Top10',
        n2,
        label_opts=opts.LabelOpts(is_show=True,position='top'),
        itemstyle_opts=opts.ItemStyleOpts(
            color=JsCode("""new echarts.graphic.LinearGradient(
            0, 0, 0, 1,[{offset: 0,color: 'rgb(255,99,71)'}, {offset: 1,color: 'rgb(32,178,170)'}])
            """
            )
        )
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title='目的地Top10'),
            xaxis_opts=opts.AxisOpts(name='景点名称',
            type_='category',                                           
            axislabel_opts=opts.LabelOpts(rotate=90),
        ),
        yaxis_opts=opts.AxisOpts(
            name='数量',
            min_=0,
            max_=120.0,
            splitline_opts=opts.SplitLineOpts(is_show=True,linestyle_opts=opts.LineStyleOpts(type_='dash'))
        ),
        tooltip_opts=opts.TooltipOpts(trigger='axis',axis_pointer_type='cross')
    )

    .set_series_opts(
        markline_opts=opts.MarkLineOpts(
            data=[
                opts.MarkLineItem(type_='average',name='均值'),
                opts.MarkLineItem(type_='max',name='最大值'),
                opts.MarkLineItem(type_='min',name='最小值'),
            ]
        )
    )
)
bar.render_notebook()

Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析

bar=(
    Bar(init_opts=opts.InitOpts(height='500px',width='1000px',theme='dark'))
    .add_xaxis(loc)
    .add_yaxis(
        '人均费用',
        price_mean2,
        label_opts=opts.LabelOpts(is_show=True,position='top'),
        itemstyle_opts=opts.ItemStyleOpts(
            color=JsCode("""new echarts.graphic.LinearGradient(
            0, 0, 0, 1,[{offset: 0,color: 'rgb(255,99,71)'}, {offset: 1,color: 'rgb(32,178,170)'}])
            """
            )
        )
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title='各景点人均费用'),
            xaxis_opts=opts.AxisOpts(name='景点名称',
            type_='category',                                           
            axislabel_opts=opts.LabelOpts(rotate=90),
        ),
        yaxis_opts=opts.AxisOpts(
            name='数量',
            min_=0,
            max_=2000.0,
            splitline_opts=opts.SplitLineOpts(is_show=True,linestyle_opts=opts.LineStyleOpts(type_='dash'))
        ),
        tooltip_opts=opts.TooltipOpts(trigger='axis',axis_pointer_type='cross')
    )

    .set_series_opts(
        markline_opts=opts.MarkLineOpts(
            data=[
                opts.MarkLineItem(type_='average',name='均值'),
                opts.MarkLineItem(type_='max',name='最大值'),
                opts.MarkLineItem(type_='min',name='最小值'),
            ]
        )
    )
)
bar.render_notebook()

Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析

出游方式分析

pie = (Pie(init_opts=opts.InitOpts(theme='dark', width='1000px', height='800px'))
       .add("", [z for z in zip(m1,n1)],
            radius=["40%", "65%"])
       .set_global_opts(title_opts=opts.TitleOpts(title="去哪儿\n\n出游结伴方式", pos_left='center', pos_top='center',
                                               title_textstyle_opts=opts.TextStyleOpts(
                                                   color='#FF6A6A', font_size=30, font_weight='bold'),
                                               ),
                        visualmap_opts=opts.VisualMapOpts(is_show=False, 
                                          min_=38,
                                          max_=641,
                                          is_piecewise=False,
                                          dimension=0,
                                          range_color=['#9400D3', '#008afb', '#ffec4a', '#FFA500','#ce5777']),
                        legend_opts=opts.LegendOpts(is_show=False, pos_top='5%'),
                        )
       .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}", font_size=12),
                        tooltip_opts=opts.TooltipOpts(trigger="item", formatter="{b}: {c}"),
                        itemstyle_opts={"normal": {
                                                    "barBorderRadius": [30, 30, 30, 30],
                                                    'shadowBlur': 10,
                                                    'shadowColor': 'rgba(0,191,255,0.5)',
                                                    'shadowOffsetY': 1,
                                                    'opacity': 0.8
                                                }
                                       })
        
                        )
pie.render_notebook()

Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析

出游时间分析

line = (
    Line()
    .add_xaxis(m4.tolist())
    .add_yaxis('',n4.tolist())
)
line.render_notebook()

Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析

2021年的旅游时间曲线大约在五月一号起伏最大,原因肯定是因为假期调休延长至4天,为了调整自己生活及工作的状态,很多人利用这个假期去旅行放松自己。

出游玩法分析

m5 = []
n5 = []
for i in range(20):
    m5.append(list[i][0])
    n5.append(list[i][1])
m5.reverse()
m6 = m5
n5.reverse()
n6 = n5

bar = (
    Bar(init_opts=opts.InitOpts(theme='dark', width='1000px',height ='500px'))
    .add_xaxis(m6)
    .add_yaxis('', n6)
    .set_series_opts(label_opts=opts.LabelOpts(is_show=True, 
                                                       position='insideRight',
                                                       font_style='italic'),
                            itemstyle_opts=opts.ItemStyleOpts(
                                color=JsCode("""new echarts.graphic.LinearGradient(1, 0, 0, 0, 
                                             [{
                                                 offset: 0,
                                                 color: 'rgb(255,99,71)'
                                             }, {
                                                 offset: 1,
                                                 color: 'rgb(32,178,170)'
                                             }])"""))
                            )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="出游玩法分析"),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=45)),
        legend_opts=opts.LegendOpts(is_show=True))
    .reversal_axis()
)
bar.render_notebook()

Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析

“摄影”和“美食”可谓与旅行息息相关,一次完整的旅行最不能缺的就是“摄影”,拍美食发到朋友圈、拍风景发到朋友圈、拍完美的自己发到朋友圈;工作之后就没有了寒暑假,所以利用周末来一次短途旅行就成为了大多数人的首选。

到此这篇关于Python爬虫入门案例之爬取去哪儿旅游景点攻略以及可视化分析的文章就介绍到这了,更多相关Python 爬取去哪儿内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python以环状形式组合排列图片并输出的方法
Mar 17 Python
Python标准库defaultdict模块使用示例
Apr 28 Python
浅谈Python的异常处理
Jun 19 Python
itchat接口使用示例
Oct 23 Python
python实时获取外部程序输出结果的方法
Jan 12 Python
python 中如何获取列表的索引
Jul 02 Python
浅析使用Python搭建http服务器
Oct 27 Python
Python使用turtle库绘制小猪佩奇(实例代码)
Jan 16 Python
python包的导入方式总结
Mar 02 Python
基于Python实现的购物商城管理系统
Apr 27 Python
Python获取江苏疫情实时数据及爬虫分析
Aug 02 Python
Pillow图像处理库安装及使用
Apr 12 Python
Python爬虫入门案例之爬取二手房源数据
Python爬虫入门案例之回车桌面壁纸网美女图片采集
Python Django模型详解
Python 阶乘详解
Oct 05 #Python
Python 实现Mac 屏幕截图详解
基于Python和openCV实现图像的全景拼接详细步骤
C3 线性化算法与 MRO之Python中的多继承
You might like
基于php在各种web服务器的运行模式详解
2013/06/03 PHP
php生成zip压缩文件的方法详解
2013/06/09 PHP
PHP移动文件指针ftell()、fseek()、rewind()函数总结
2014/11/18 PHP
PHP的PDO常用类库实例分析
2016/04/07 PHP
使用PHP连接数据库_实现用户数据的增删改查的整体操作示例
2017/09/01 PHP
JavaScript 学习笔记(六)
2009/12/31 Javascript
javascript之AJAX框架使用说明
2010/04/24 Javascript
javascript克隆对象深度介绍
2012/11/20 Javascript
JS继承--原型链继承和类式继承
2013/04/08 Javascript
Jquery检验手机号是否符合规则并根据手机号检测结果将提交按钮设为不同状态
2015/11/26 Javascript
基于javascript如何传递特殊字符
2015/11/30 Javascript
jQuery javascript获得网页的高度与宽度的实现代码
2016/04/26 Javascript
微信小程序中的swiper组件详解
2017/04/14 Javascript
基于es6三点运算符的使用方法(实例讲解)
2017/10/12 Javascript
在JavaScript中如何访问暂未存在的嵌套对象
2019/06/18 Javascript
JavaScript使用百度ECharts插件绘制饼图操作示例
2019/11/26 Javascript
vue递归获取父元素的元素实例
2020/08/07 Javascript
[33:42]LGD vs OG 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
python正则表达式的使用
2017/06/12 Python
深入理解Python中的super()方法
2017/11/20 Python
Python实现批量修改图片格式和大小的方法【opencv库与PIL库】
2018/12/03 Python
python 对多个csv文件分别进行处理的方法
2019/01/07 Python
Python3.4学习笔记之类型判断,异常处理,终止程序操作小结
2019/03/01 Python
Python 获取numpy.array索引值的实例
2019/12/06 Python
Python sys模块常用方法解析
2020/02/20 Python
在 Pycharm 安装使用black的方法详解
2020/04/02 Python
python初步实现word2vec操作
2020/06/09 Python
深入浅析HTML5中的SVG
2015/11/27 HTML / CSS
Skip Hop官网:好莱坞宝宝挚爱品牌
2018/06/17 全球购物
世界领先的电子书网站:eBooks.com(在线购买小说、非小说和教科书)
2019/03/30 全球购物
C#面试常见问题
2013/02/25 面试题
自我评价格式
2014/01/06 职场文书
校园歌手大赛策划书
2014/01/17 职场文书
法院授权委托书范文
2014/08/02 职场文书
2014年个人技术工作总结
2014/12/08 职场文书
Vue+Element UI实现概要小弹窗的全过程
2021/05/30 Vue.js