利用pyquery以及requests库爬取携程酒店(上海)部分信息

爬取内容为:酒店名,位置,评分,推荐用户的比例,点评数以及推荐理由

                                                                                 图1

首先要对页面元素进行分析

                                                                                 图2

        div中类选择器名为(.hotel_new_list J_HotelListBaseCell)的框架为各酒店信息的框架,且各酒店框架相同,名为hotel_list的id选择器为各酒店框架的父节点,假设要提取酒店名则因根据对应的类选择器定位其酒店名所在的位置,如根据名为label_selection的选择器定位酒店名。

                                                                                图3

        而要提取其评级得分应根据其祖先节点.hotel_item_judge no_comment及其他祖先节点从而得到评级得分

 

#这里只获取一页的数据,由于该页面的url并不会随着页码的增加而变换,所以需要另外一些技术(也可能是我太菜了,不知道该怎么做,还有就是为什么不获取酒店价格?因为酒店价格最重要所以加入了反扒手段,不好扒,当然之后会把这些技术都加进来)
import requests
from pyquery import PyQuery as pq
import csv
#url
url = "https://hotels.ctrip.com/hotel/shanghai2#ctm_ref=hod_hp_sb_lst"
#简单的header信息,只设置了代理
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}

html = requests.get(url,headers = headers).text
#print(html)

doc = pq(html)
#对应所有酒店对应的框架
hotel = doc('#hotel_list .hotel_new_list.J_HotelListBaseCell').items()

#创建文件
hotel_file = open('hotel.csv','a+',encoding = "utf-8",newline= '')
writer = csv.writer(hotel_file)
writer.writerow(('酒店名','位置','评价等级','分数','推荐人百分比','推荐人数','推荐评价'))
#循环得到各酒店信息
for item in hotel:
    #图2中蓝色那一行字上方有精选两个,这两个字并不属于我们要爬取的范围,
    #需要去除,所以remove class为label_selection的标签
    hotel_name = item('.hotel_item_name .hotel_name a').remove('.label_selection').text()
    #而位置后面有地图两个字,同样去除
    place = item('.hotel_item_name .hotel_item_htladdress').remove('.link_map.J_showPopMap.icon_list_map').text()
    #获取评级(超棒,棒等)
    pingjia = item('.hotel_item_judge.no_comment .hotel_level').text()
    #获取评价分数
    score = item('.hotel_item_judge.no_comment .hotel_value').text()
    #获取推荐此酒店用户的比例
    percent = item('.hotel_item_judge.no_comment .total_judgement_score').text()
    #获取用户总评价数
    number = item('.hotel_item_judge.no_comment .hotel_judgement').text()
    #获取推荐理由
    recommand = item('.hotel_item_judge.no_comment .recommend').remove('br').text()
    print(hotel_name,place,pingjia,score,percent,number,recommand)
    #写入文件
    writer.writerow((hotel_name,place,pingjia,score,percent,number,recommand))
    
hotel_file.close()

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值