Python 爬取携程景点用户评论信息教程_以武汉木兰草原景点为例

Python 爬取携程景点评论教程

话不多说,先看结果,满意再点赞+关注+收藏!

这是爬取武汉木兰草原的用户评论

在这里插入图片描述

携程木兰草原页面网址

https://you.ctrip.com/sight/wuhan145/50956.html

爬取中

爬取中

保存为CSV文件

爬取后保存为.CSV文件


上代码!

编写爬虫类

// An highlighted block
import csv
import json
import time

import requests
class Reptile:       #创建一个爬虫类,方便在其他文件中调用
    def __init__(self, postURL, user_agent, poiId, cid, startPageIndex, endPageIndex, file):
        self.postURL = postURL
        self.user_agent = user_agent
        self.poiId = poiId
        self.cid = cid
        #上面这些对应着包中的头部信息填就是了
        self.startPageIndex = startPageIndex     #开始爬取的页码
        self.endPageIndex = endPageIndex         #结束爬取的页码
        self.file = file           #保存记录的.csv文件的文件名,一定要将后缀名也写上,如:"****.csv"
        self.dataListCSV = []      #用来暂存爬取结果,是一个二维列表,dataListCSV中的每一个元素对应一条记录,便于写入CSV文件

    def get(self):
        for i in range(int(self.startPageIndex), int(self.endPageIndex)+1):       #爬取第 i 页
            requestParameter = {
                'arg': {'channelType': '2',
                        'collapseType': '0',
                        'commentTagId': '0',
                        'pageIndex': str(i),    #爬取的评论页面的页码索引
                        'pageSize': '10',       #每页的评论数量
                        'poiId': str(self.poiId),   #景点地址代码
                        'sortType': '1',
                        'sourceType': '1',
                        'starType': '0'},

                'head': {'auth': "",
                         'cid': self.cid,   #不同景点的cid不同,因此需要自行设置
                         'ctok': "",
                         'cver': "1.0",
                         'extension': [],
                         'lang': "01",
                         'sid': "8888",
                         'syscode': "09",
                         'xsid': ""}
            }
            html = requests.post(self.postURL, data=json.dumps(requestParameter)).text
            html = json.loads(html)    #得到第i页字典形式的全部评论数据
            for element in html["result"]["items"]:             #处理景色、趣味、性价比得分
                if element['scores']:
                    if element['scores'][0]:
                        sceneryScore = str(element['scores'][0]["score"])
                    else:
                        sceneryScore = ""
                    if element['scores'][1]:
                        interestScore = str(element['scores'][2]["score"])
                    else:
                        interestScore = ""
                    if element['scores'][3]:
                        costScore = str(element['scores'][4]["score"])
                    else:
                        costScore = ""
                else:
                    sceneryScore = ""
                    interestScore = ""
                    costScore = ""

                #处理评论时间的格式
                publishTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(element["publishTime"][6:16])))
                self.dataListCSV.append([len(self.dataListCSV)+1, element["userInfo"]["userNick"], publishTime, element["score"], sceneryScore, interestScore, costScore, element["districtId"], element["content"]])

            print(f"页面 {i} 已爬取", type(html))
            time.sleep(4)
        print(self.dataListCSV)
        with open(self.file, "w+", encoding="utf8", newline="") as f: #将dataListCSV列表内容写入.csv文件中
            write = csv.writer(f)
            write.writerow(["序号","昵称", "发布日期", "总体给分", "景色分", "趣味分", "性价比分", "地区编号", "评论内容"])
            write.writerows(self.dataListCSV)

调用爬虫

// An highlighted block
#我的Reptile类是放在dataProcurement包下的

from dataProcurement.Reptile import Reptile 

postURL = "https://m.ctrip.com/restapi/soa2/13444/json/getCommentCollapseList?_fxpcqlniredt=09031083119044546256"
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30"
poiId = 83520
cid = "09031083119044546256"
startPageIndex = 1
endPageIndex = 20

reptile = Reptile(postURL, user_agent, poiId, cid, startPageIndex, endPageIndex, "mlcy.csv")
reptile.get()

浏览器对应包结构如下图

找到networks(网络)中的getCommentCollapseList包,postURL见标头部分的请求URL,写到https://m.ctrip.com/restapi/soa2/13444/json/getCommentCollapseList?_fxpcqlniredt=09031083119044546256

即可,不要全写。
poiId和cid见请求负载部分,
user_agent就不用再多说了,能找到这篇文章的朋友应该都懂。

在这里插入图片描述

好了,到此你已经成功爬取到了携程景点的用户评论信息!

  • 7
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
【资源说明】 基于python实现爬取携程景点数据与评论数据源码+项目说明.zip 基于python实现爬取携程景点数据与评论数据源码+项目说明.zip 基于python实现爬取携程景点数据与评论数据源码+项目说明.zip 1、该资源内项目代码都是经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载使用,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能。 爬取结果有两部分:`data/poi.csv`为**景点数据**,`data/comment/{id}.csv`为对应ID的景点的**评论数据** 评论内容的爬取有两种方法: 将`config.ini`中的`isCrawlComment`置为1,运行`poi_crawl.py`文件,在爬取 景点数据 的过程中爬取 评论数据 将`config.ini`中的`isCrawlComment`置为0,运行`poi_crawl.py`文件,在爬取 景点数据 结束后运行再运行`comment_crawl.py`文件,获取 景点数据 中的所有景点评论 每次运行前都会在同一文件夹下复制一份上一次爬取景点结果的备份,名为`back.csv` 数据中 **价格**、**最低价格**为response中的数据,暂无参考价值 后面四种人群门票价格为**预估的销量加权平均价格**,如果有不同需求可以修改 `GetTicketPrice` 函数。(返回的数据为所有的门票价格) 景点数据中的**开放时间**与**优惠政策** 数据的格式为json格式 爬取评论数据 格式为: **用户ID** **评论文本** **发送时间戳** **赞同数**
携程网站利用python爬取评论数据的过程可以分为以下几步: 1. 确定需要爬取的酒店或景点的链接地址。 2. 利用 Python 中的 requests 库向该链接发送请求,获取网页源代码。 3. 利用 BeautifulSoup 或者其他解析库解析网页源代码,获取评论数据所在的 HTML 标签和属性。 4. 提取评论数据,并保存到本地文件或者数据库中。 具体的代码实现可以参考以下步骤: 1. 导入相关库和模块: ```python import requests from bs4 import BeautifulSoup import json ``` 2. 定义需要爬取的酒店或景点的链接地址: ```python url = 'https://hotels.ctrip.com/hotel/2565505.html#ctm_ref=hod_sr_lst_dl_n_1_1' ``` 3. 发送请求,获取网页源代码: ```python headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} response = requests.get(url, headers=headers) html = response.text ``` 4. 解析网页源代码,获取评论数据所在的 HTML 标签和属性: ```python soup = BeautifulSoup(html, 'lxml') comments = soup.find_all('div', {'class': 'comment_item'}) ``` 5. 提取评论数据,并保存到本地文件或者数据库中: ```python result = [] for comment in comments: user = comment.find('a', {'class': 'user_comment'}).get_text() content = comment.find('div', {'class': 'J_commentDetail'}).get_text().strip() date = comment.find('span', {'class': 'time'}).get_text()[:10] score = comment.find('span', {'class': 'score'}).get_text() result.append({'user': user, 'content': content, 'date': date, 'score': score}) with open('comments.json', 'w', encoding='utf-8') as fp: json.dump(result, fp, ensure_ascii=False) ``` 以上就是利用 Python 爬取携程网站评论数据的过程和代码实现。需要注意的是,爬虫过程中需要遵守相关法律法规,不得进行非法爬取和使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

同稚君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值