去哪儿旅行,景点热度排行爬取案例

本案例对旅游景点的热度,点评数量,排行等进行了爬取,后期数据处理部分还有提高空间,请读者自行编写。

# -*- coding: utf-8 -*-
"""
Created on Wed Apr  3 17:48:21 2019

@author: iHJX_Alienware
"""

import requests
from bs4 import BeautifulSoup

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

print('导入模块')

import matplotlib.pyplot as plt
import seaborn as sns

plt.rcParams['font.sans-serif'] = ['SimHei']  
# Matplotlib中设置字体-黑体,解决Matplotlib中文乱码问题
plt.rcParams['axes.unicode_minus'] = False    
# 解决Matplotlib坐标轴负号'-'显示为方块的问题

#获取连接网页数据
def get_urls(n):
    return ['https://travel.qunar.com/p-cs300153-rizhao-jingdian-1-' + str(i+1) for i in range(n)]
    # 创建函数,获取分页网址
#获取具体需要的参数
def get_informations(u):
    ri = requests.get(u)
        # requests访问网站
    soupi = BeautifulSoup(ri.text,'lxml')
        # bs解析页面
    infori = soupi.find('ul',class_="list_item clrfix").find_all('li')
        # 获取列表内容
    
    datai = []
    n=0
    for i in infori:
        n+=1
        #print(i.text)
        dic = {}
        dic['lat'] = i['data-lat']
        dic['lng'] = i['data-lng']
        dic['景点名称'] = i.find('span',class_="cn_tit").text
        dic['攻略提到数量'] = i.find('div',class_="strategy_sum").text
        dic['点评数量'] = i.find('div',class_="comment_sum").text
        dic['景点排名'] = i.find('span',class_="ranking_sum").text
        dic['星级'] = i.find('span',class_="total_star").find('span')['style'].split(':')[1]
        datai.append(dic) #列表包字典
        # 分别获取字段内容
        #print('已采集%s条数据' %(n*10))
    return datai
    
    # 构建页面爬虫
#标准化某一指标便于对比
def normalization(dfi, col):
    dfi[col + "_nor"] = (dfi[col] - dfi[col].min())/(dfi[col].max() - dfi[col].min())


if __name__ == '__main__':
    #获取多页网页数据
    url_lst = get_urls(20)

    #将数据转化为dataframe格式便于处理
    df = pd.DataFrame()
    for u in url_lst:
        dfi = pd.DataFrame(get_informations(u))
        df = pd.concat([df,dfi])
        df.reset_index(inplace = True,drop = True)
        # 采集数据


    #对dataframe中的数据格式进行调整
    df['lng'] = df['lng'].astype(np.float)
    df['lat'] = df['lat'].astype(np.float)
    df['点评数量'] = df['点评数量'].astype(np.int)
    df['攻略提到数量'] = df['攻略提到数量'].astype(np.int)
        # 字段类型处理
    df['星级'] = df['星级'].str.replace('%','').astype(np.float)
        # 星级字段处理
    df['景点排名'] = df['景点排名'].str.split('第').str[1]
    df['景点排名'].fillna(value = 0,inplace = True)

    normalization(df, '点评数量')
    #输出为excel形式
    df.to_excel("./result.xlsx")

   
    

效果图,有什么地方看不懂,可以留言给我

在这里插入图片描述

这个任务可以通过爬取去哪儿网站的酒店列表和热门城市页面来实现。以下是一个示例爬虫代码(使用Python和BeautifulSoup库): ```python import requests from bs4 import BeautifulSoup # 首先,我们需要获取全国热门城市列表 url = 'https://www.qunar.com/' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') hot_city_tags = soup.select('.hot_city_list a') hot_cities = [tag.text for tag in hot_city_tags] # 接下来,我们需要遍历热门城市并获取酒店列表 top_hotels = [] for city in hot_cities: # 构造城市页面的URL url = f'https://hotel.qunar.com/city/{city}/' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') hotel_tags = soup.select('.b_hlist_item') hotels = [{'name': tag.select_one('.e_title a').text, 'rank': tag.select_one('.level em').text} for tag in hotel_tags] # 将获取到的酒店列表按照排名排序,并取前10000家酒店 sorted_hotels = sorted(hotels, key=lambda h: int(h['rank'])) top_hotels += sorted_hotels[:10000 - len(top_hotels)] if len(top_hotels) >= 10000: break # 打印前10家酒店的名称和排名 for i in range(10): print(f"{i+1}. {top_hotels[i]['name']}, 排名: {top_hotels[i]['rank']}") ``` 这个爬虫首先获取了去哪儿网站的首页,然后从热门城市列表中获取城市名称。接下来,它遍历了每个城市页面,从中获取了酒店列表,并将结果按照排名排序。最后,它打印了前10家酒店的名称和排名。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值