当前位置:   article > 正文

python爬虫之爬取携程景点评价(5)_爬取某一景点的好评和差评数据

爬取某一景点的好评和差评数据

 一、景点部分评价爬取

【携程攻略】携程旅游攻略,自助游,自驾游,出游,自由行攻略指南 (ctrip.com)

  1. import requests
  2. from bs4 import BeautifulSoup
  3. if __name__ == '__main__':
  4. url = 'https://m.ctrip.com/webapp/you/commentWeb/commentList?seo=0&businessId=22176&businessType=sight&hideStatusBar=1&DistrictName=%E9%BB%84%E9%BE%99%E6%BA%AA&isBack=yes&from=https%3A%2F%2Fm.ctrip.com%2Fwebapp%2Fyou%2Fgspoi%2Fsight%2F104%2F0.html%3FpoiId%3D81011%26seo%3D0%26isHideNavBar%3DYES%26scene%3DDISTRICT%26ctm_ref%3Dch5_hp_bs_lst&'#目标访问网站url
  5. header = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0"}
  6. req = requests.get(url=url,headers = header)#获取该网页内容
  7. req.encoding = 'utf-8'#防止中文乱码,还可以改成gbk
  8. html = req.text
  9. bes = BeautifulSoup(html,"lxml")
  10. div_contents = bes.find_all('div', class_='content_wrap')#找到里面的所有div标签
  11. if div_contents:
  12. count = 1
  13. for div_content in div_contents:
  14. all_info = div_content.text
  15. print(f'{count}: {all_info}')
  16. count += 1
  17. else:
  18. print('未找到指定的<div class="content_wrap">标签')

二、景点所有评价爬取

        通过搜索,发现请求方法不在是get,而是post,且预览并得不到我们需要的评论,反而是响应界面才可以,则针对这种情况,我们需要重新更改代码。

更改代码如下 

  1. import requests
  2. import json
  3. import pandas as pd
  4. from tqdm import tqdm
  5. userNames = []
  6. commentDetails = []
  7. commentTimes = []
  8. total_pages = 1
  9. for pagen in tqdm(range(0, total_pages), desc='爬取进度', unit='页'):
  10. #payload参数实质上就是网络下的负载
  11. payload = {
  12. "arg": {
  13. "channelType": 7,
  14. "collapseTpte": 1,
  15. "commentTagId": 0,
  16. "pageIndex": pagen,
  17. "pageSize": 10,
  18. "resourceId":22176,
  19. "resourceType":11,
  20. "sourseType": 1,
  21. "sortType": 3,
  22. "starType": 0
  23. },
  24. "head": {
  25. "cid": "09031081213865125571",
  26. "ctok": "",
  27. "cver": "1.0",
  28. "lang": "01",
  29. "sid": "8888",
  30. "syscode": "09",
  31. "auth": "",
  32. "xsid": "",
  33. "extension": []
  34. }
  35. }
  36. #网络的标头中的url路径,采用POST请求方法,其?后面的内容就是payload
  37. postUrl = "https://m.ctrip.com/restapi/soa2/13444/json/getCommentCollapseList"
  38. html = requests.post(postUrl, data=json.dumps(payload)).text
  39. html_1 = json.loads(html)#html_1实质就是网络下面的响应界面
  40. # 检查响应中是否存在'items'
  41. if 'items' in html_1["result"]:
  42. commentItems = html_1["result"]["items"]
  43. for i in range(0, len(commentItems)):
  44. # 在访问元素之前检查当前项是否不为None
  45. if commentItems[i] is not None and 'userInfo' in commentItems[i] and 'userNick' in commentItems[i][
  46. 'userInfo']:
  47. userName = commentItems[i]['userInfo']['userNick']
  48. commentDetail = commentItems[i]['content']
  49. commentTime = commentItems[i]['publishTypeTag']
  50. userNames.append(userName)
  51. commentDetails.append(commentDetail)
  52. commentTimes.append(commentTime)
  53. # 创建 DataFrame
  54. df = pd.DataFrame({
  55. '用户评论内容': commentDetails,
  56. '用户名': userNames,
  57. '用户评论时间': commentTimes
  58. })
  59. # 保存到 Excel 文件
  60. df.to_excel('只爬黄龙溪评论1223url.xlsx', index=False, encoding='utf-8')

 

三、不同景点所有评价爬取

 可以看出,不同景点的resourceId不一样,即更改diamagnetic中的resourceId的数字即可

四、URL编码很乱如何解码

UrlEncode编码/UrlDecode解码 - 站长工具 (chinaz.com)

五、No module named 'pandas'问题解决

ModuleNotFoundError: No module named 'pandas'

常用源:

清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/616415
推荐阅读
相关标签
  

闽ICP备14008679号