Python爬蟲實戰:爬取【某旅游交通出行類網站中國內熱門景點】的評論數據,使用Re、BeautifulSoup與Xpath三種方式解析數據,代碼完整

一、分析爬取網頁:

1、網址

https://travel.qunar.com/

2、 打開網站,找到要爬取的網頁

https://travel.qunar.com/p-cs299979-chongqing

在這里插入圖片描述

進來之后,找到評論界面,如下所示:在這里我選擇驢友點評數據爬取

在這里插入圖片描述

點擊【驢友點評】,進入最終爬取的網址:https://travel.qunar.com/p-cs299979-chongqing-gaikuang-2-1-1#lydp

在這里插入圖片描述

3、 進入開發者模型(F12),分析網頁,找到數據接口

(1)點擊網絡
在這里插入圖片描述
(2)點擊左邊網頁中的第二、第三、第四…頁,觀察右邊的變化:發現右邊有一地址帶有頁數和每頁數據量,因此點擊該地址在網頁中打開發現帶有json格式的數據并且數據對應就是該頁的內容,如下所示:

接口地址:https://travel.qunar.com/place/api/html/comments/dist/299979?sortField=1&pageSize=10&page=1

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

并且只要變換接口地址后面的page就可以獲取不同頁數的數據。同理,我們發現【熱門攻略】也是如此,因此將其順帶也爬取出來,數據接口地址:https://travel.qunar.com/place/api/html/books/dist/299979?sortField=0&pageSize=10&page=2

在這里插入圖片描述

三、請求網頁數據并將數據進行保存

當我們確定了真實數據的URL后,這里便可以用requests的get或post方法進行請求網頁數據。關于requests庫的更多使用方式,大家可以前往(https://requests.readthedocs.io/zh_CN/latest/ 或 https://www.cnblogs.com/aaronthon/p/9332757.html)查看。

1、分析爬取的json數據,為提取數據做準備,如下圖所示:json數據里提取的data數據是我們所需要的數據,而data數據就是html形式的字符串,打開網頁與其對比,發現最后需要獲取的數據在li標簽里面,因此我們選擇對其進行提取:采用正則與Beautiful Soup、xpath來解析數據

在這里插入圖片描述
在這里插入圖片描述

2、正則re提取數據,完整代碼如下:

# coding:utf-8
import requests,time,os,openpyxl,re
from openpyxl import Workbook
import mysql.connectorclass RenrenLogin(object):def __init__(self):# 設置存儲數據文件路徑self.excellj = ''self.excellj1 = r"C:\XXXXXXXXXXXX\qne1.xlsx"self.excellj2 = r"C:\XXXXXXXXXXXX\qne2.xlsx"def get_html(self, url,names):# 因此f12查看時,數據為json格式data1 = requests.get(url=url).json()self.parse_html(data1,names)def parse_html(self, data,names):L1,L2,L3,L4,L5,L6,L7,L8 = [],[],[],[],[],[],[],[]if(names == "熱門攻略"):userurl = re.findall(r'<a rel="nofollow" class="face" target="_blank" href="(.*?)".*?</a>', data["data"],re.S)                     # 用戶url地址userpicture = re.findall(r'<img class="imgf" width="50" height="50" src="(.*?)"', data["data"], re.S)                              # 用戶頭像usertitle = re.findall(r'<img class="imgf".*?title="(.*?)"', data["data"], re.S)                                                   # 用戶昵稱L1 = re.findall(r'<h3 class="tit"><a data-beacon="travelbook" target="_blank" href=".*?">(.*?)</h3>',data["data"], re.S)           # 用戶發表標題for i in L1:L2.append(''.join(re.findall('[\u4e00-\u9fa5]', i)))usersubject = L2userinfourl =  re.findall(r'<a data-beacon="travelbook" target="_blank" href="(.*?)"', data["data"], re.S)                         # 用戶詳情L3 =  re.findall(r'<p class="places">(.*?)<span class="colOrange">(.*?)</span></p><p class="places">',data["data"], re.S)          # 用戶途徑for i in L3:L4.append(i[1])useraddress = L4L5 = re.findall(r'<p class="places">途經:(.*?)</p><ul class="pics">', data["data"], re.S)                                          # 用戶行程for i in L5:L6.append(''.join(re.findall('[\u4e00-\u9fa5: ]',i)))userstroke = L6L7 = re.findall(r'<ul class="pics">(.*?)</li></ul>', data["data"], re.S)                                                           # 用戶發表圖片for i in L7:L8.append(re.findall(r'src="(.*?)"', i, re.S))userimages = L8userdz = re.findall(r'<i class="iconfont">&#xe09d;</i><span>(.*?)</span>', data["data"], re.S)                                     # 用戶點贊數量userpl = re.findall(r'<i class="iconfont">&#xf04f;</i><span>(.*?)</span>', data["data"], re.S)                                     # 用戶評論數量for i in range(len(usertitle)):alldata = []alldata.append(usertitle[i])alldata.append(usersubject[i])alldata.append(useraddress[i])alldata.append(userstroke[i])alldata.append(userdz[i])alldata.append(userpl[i])alldata.append(userpicture[i])alldata.append(userurl[i])alldata.append(userinfourl[i])alldata.append(str(userimages[i]))self.parse_excel(alldata,names)else:usertitle = re.findall(r'<div class="e_comment_usr_name"><a rel="nofollow" href=".*?" target="_blank">(.*?)</a></div>',data["data"], re.S)userurl = re.findall(r'<div class="e_comment_usr_name"><a rel="nofollow" href="(.*?)" target="_blank">.*?</a></div>',data["data"], re.S)usercomtit = re.findall(r'<a data-beacon="comment_title" href=".*?" target="_blank">(.*?)</a><span class="icon_gold_camel">',data["data"], re.S)L1 = re.findall(r'<div class="e_comment_content">(.*?)閱讀全部</a></div>', data["data"], re.S)for i in L1:L2.append(''.join(re.findall('[\u4e00-\u9fa5 ]',i)))usercomment = L2L3 = re.findall(r'<ul class="base_fl" ><li><a rel="nofollow" data-beacon="comment_pic" href=".*?" target="_blank">.*?張》',data["data"], re.S)for i in L3:L4.append(re.findall(r'src="(.*?)"', i, re.S))if(len(L4) < 10 ):for i in range(10-len(L4)):L4.append('空')userimages = L4else:userimages = L4userpicture = re.findall(r'<div class="e_comment_usr_pic"><a rel="nofollow" href=".*?" target="_blank"><img .*? src="(.*?)" /></a></div>',data["data"], re.S)for i in range(len(usertitle)):alldata = []alldata.append(usertitle[i])alldata.append(usercomtit[i])alldata.append(usercomment[i])alldata.append(userurl[i])alldata.append(str(userimages[i]))alldata.append(userpicture[i])self.parse_excel(alldata, names)return Truedef parse_excel(self, alldata,names):if(names == "熱門攻略"):self.excellj = self.excellj1filetitle = ["用戶昵稱","用戶發表主題","用戶途徑","用戶路徑","用戶點贊數","用戶評論數","用戶頭像","用戶主頁地址","用戶詳情地址","用戶發布圖片"]else:self.excellj = self.excellj2filetitle = ["用戶昵稱","用戶發表主題","用戶評論","用戶主頁地址","用戶發布圖片","用戶頭像"]if not os.path.exists(self.excellj):workbook = Workbook()workbook.save(self.excellj)wb = openpyxl.load_workbook(self.excellj)wa = wb.activewa.append(filetitle)wa.append(alldata)wb.save(self.excellj)else:wb = openpyxl.load_workbook(self.excellj)wa = wb.activewa.append(alldata)wb.save(self.excellj)return Truedef main(self, ):UrlList = ["https://travel.qunar.com/place/api/html/books/dist/299979?sortField=0&pageSize=10&page=","https://travel.qunar.com/place/api/html/comments/dist/299979?sortField=1&pageSize=10&page="]names = ["熱門攻略","驢友點評"]for i in range(len(UrlList)):for j in range(1,3):url = UrlList[i] + str(j)self.get_html(url,names[i])print(f"重慶地區【{names[i]}】第{j}頁數據爬取結束!!!")time.sleep(10)if __name__ == '__main__':spider = RenrenLogin()spider.main()

結果如下所示:
【熱門攻略】:
在這里插入圖片描述
【驢友點評】:
在這里插入圖片描述

3、BeautifulSoup提取數據,完整代碼如下:這里只爬取了驢友點評,熱門攻略也是一樣方法

# coding:utf-8
import requests,time,os,openpyxl,re
from openpyxl import Workbook
from bs4 import BeautifulSoupclass RenrenLogin(object):def __init__(self):self.excellj = r"C:\XXXXXXXXXXXX\qne1.xlsx"def get_html(self, url):data1 = requests.get(url=url).json()self.parse_html(data1)def parse_html(self, data):soup = BeautifulSoup(data["data"], 'lxml')L1,L2,L3,L4,L5,L6,L7,L8 = [],[],[],[],[],[],[],[]sellList1 = soup.find_all('div',class_="e_comment_usr_name")for i in sellList1:soup1 = BeautifulSoup(str(i), 'lxml')div_tag = soup1.find('div')a_tags = div_tag.find('a')userhref = a_tags.get('href')L1.append(userhref)L2.append(a_tags.text)usertitle = L2userurl = L1sellList2 = soup.find_all('div',class_="e_comment_title")for i in sellList2:soup1 = BeautifulSoup(str(i), 'lxml')div_tag = soup1.find('div')a_tags = div_tag.find('a')L3.append(a_tags.text)usercomtit = L3sellList3 = soup.find_all('div',class_="e_comment_content")for i in sellList3:str1 = ''soup1 = BeautifulSoup(str(i), 'lxml')div_tag = soup1.find('div')a_tags = div_tag.find_all('p')for tag in a_tags:str1 = str1 + tag.text +' 'L4.append(str1)usercomment = L4sellList4 = soup.find_all('div', class_="e_comment_imgs clrfix")L1 = []for i in sellList4:str1 = ''soup1 = BeautifulSoup(str(i), 'lxml')div_tag = soup1.find('div')a_tags = div_tag.find_all('img')for j in a_tags:str1 = str1 + j.get("src") + ' , 'L5.append(str1)if (len(L5) < 10):for i in range(10 - len(L4)):L5.append('空')userimages = L5else:userimages = L5sellList5 = soup.find_all('div',class_="e_comment_usr_pic")for i in sellList5:soup1 = BeautifulSoup(str(i), 'lxml')div_tag = soup1.find('div')a_tags = div_tag.find('a')userhref = a_tags.get('href')L6.append(userhref)userpicture = L6for i in range(len(usertitle)):alldata = []alldata.append(usertitle[i])alldata.append(usercomtit[i])alldata.append(usercomment[i])alldata.append(userurl[i])alldata.append(str(userimages[i]))alldata.append(userpicture[i])self.parse_excel(alldata)return Truedef parse_excel(self, alldata):filetitle = ["用戶昵稱","用戶發表主題","用戶評論","用戶主頁地址","用戶發布圖片","用戶頭像"]if not os.path.exists(self.excellj):workbook = Workbook()workbook.save(self.excellj)wb = openpyxl.load_workbook(self.excellj)wa = wb.activewa.append(filetitle)wa.append(alldata)wb.save(self.excellj)else:wb = openpyxl.load_workbook(self.excellj)wa = wb.activewa.append(alldata)wb.save(self.excellj)return Truedef main(self, ):UrlList = ["https://travel.qunar.com/place/api/html/comments/dist/299979?sortField=1&pageSize=10&page="]names = ["驢友點評"]for i in range(len(UrlList)):for j in range(1,3):url = UrlList[i] + str(j)self.get_html(url)print(f"重慶地區【{names[i]}】第{j}頁數據爬取結束!!!")time.sleep(10)if __name__ == '__main__':spider = RenrenLogin()spider.main()

【驢友點評】:
在這里插入圖片描述

4、Xpath提取數據,完整代碼如下:這里只爬取了熱門攻略,驢友點評也是一樣方法

# coding:utf-8
import requests,time,os,openpyxl,re
from openpyxl import Workbook
from lxml import etreeclass RenrenLogin(object):def __init__(self):self.excellj = r"C:\XXXXXXXXXX\qne1.xlsx"def get_html(self, url):data1 = requests.get(url=url).json()self.parse_html(data1)def parse_html(self, data):L1,L2,L3,L4,L6 = [],[],[],[],[]html = etree.HTML(data["data"])usertitle = html.xpath('//span[@class="user_name"]/a/text()')userurl = html.xpath('//span[@class="user_name"]/a/@href')userpicture = html.xpath('//img[@class="imgf"]/@src')for i in range(10):userzt1 = html.xpath('//h3[@class="tit"]')[i]userzt2 = userzt1.xpath('./a/text()')str1 = ''for j in range(len(userzt2)):str1 = str1 + userzt2[j]L1.append(str1)usersubject = L1for i in range(10):useraddres1 = html.xpath('//li[@class="list_item"]')[i]useraddres2 = useraddres1.xpath('p/text()')[0]useraddres3 = html.xpath('//span[@class="colOrange"]')[i]useraddres4 = useraddres3.xpath('./text()')[0]L2.append(useraddres2 + useraddres4)useraddress = L2for i in range(10):userstroke1 = html.xpath('//li[@class="list_item"]')[i]userstroke2 = userstroke1.xpath('p[4]/text()')L3.append(userstroke2)userstroke = L3for i in range(10):userimages = html.xpath('//ul[@class="pics"]')[i]L5 = []for j in range(1, len(userimages) + 1):L5.append(userimages.xpath(f'li[{j}]/a/img/@src'))L4.append(L5)userimages = L4userdz = html.xpath('//span[@class="icon_view"]/span/text()')userpl = html.xpath('//span[@class="icon_love"]/span/text()')for i in range(len(usertitle)):alldata = []alldata.append(usertitle[i])alldata.append(usersubject[i])alldata.append(useraddress[i])alldata.append(str(userstroke[i]))alldata.append(userdz[i])alldata.append(userpl[i])alldata.append(userpicture[i])alldata.append(userurl[i])alldata.append(str(userimages[i]))self.parse_excel(alldata)return Truedef parse_excel(self, alldata):filetitle = ["用戶昵稱","用戶發表主題","用戶途徑","用戶路徑","用戶點贊數","用戶評論數","用戶頭像","用戶主頁地址","用戶發布圖片"]if not os.path.exists(self.excellj):workbook = Workbook()workbook.save(self.excellj)wb = openpyxl.load_workbook(self.excellj)wa = wb.activewa.append(filetitle)wa.append(alldata)wb.save(self.excellj)else:wb = openpyxl.load_workbook(self.excellj)wa = wb.activewa.append(alldata)wb.save(self.excellj)return Truedef main(self, ):UrlList = ["https://travel.qunar.com/place/api/html/books/dist/299979?sortField=0&pageSize=10&page="]names = ["熱門攻略"]for i in range(len(UrlList)):for j in range(1,3):url = UrlList[i] + str(j)self.get_html(url)print(f"重慶地區【{names[i]}】第{j}頁數據爬取結束!!!")time.sleep(10)if __name__ == '__main__':spider = RenrenLogin()spider.main()

結果如下:
在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/10028.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/10028.shtml
英文地址,請注明出處:http://en.pswp.cn/web/10028.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

騰訊共享WiFi項目的加盟方式有哪些?

在這個互聯互通的時代&#xff0c;共享經濟的浪潮正以前所未有的力量席卷全球&#xff0c;而騰訊作為中國互聯網巨頭之一自然不會錯過這場盛宴。其推出的騰訊共享WiFi項目自問世以來就備受矚目&#xff0c;它不僅為用戶提供便捷的上網服務&#xff0c;更為創業者打開了一個全新…

untiy 為預制體動態加載光照貼圖

unity版本為2021.8 預制體不能攜帶光照貼圖信息&#xff0c;只能我們自己準備了 多方查找加自己摸索終于找到了適合新版本的解決方案&#xff0c;直接貼代碼 將這個腳本掛到預制體的最上級 using System.Collections; using System.Collections.Generic; using UnityEditor; …

美顏SDK是什么?深度學習技術在直播美顏SDK中的應用探析

美顏SDK的出現為直播、視頻通話等應用提供了強大的美顏功能。接下來&#xff0c;我們將一同探討美顏SDK的概念&#xff0c;以及深度學習技術在直播美顏SDK中的應用。 一、什么是美顏SDK&#xff1f; 美顏SDK是一種軟件開發工具包&#xff0c;旨在為開發者提供便捷而強大的美顏…

四大誤區:中臺產品時設計你中招了幾個?

01 誤區一&#xff1a;管理系統分析工具數字化中臺 傳統企業在經營管理過程中會根據業務或管理需求&#xff0c;不斷添加和升級諸如OA、CRM等不同類別的管理系統。 為了更好地響應前臺的業務需求&#xff0c;有些企業成立了新的或擴大、加強了原有的技術部門&#xff0c;由…

LeetCode 題目 116:填充每個節點的下一個右側節點指針

作者介紹&#xff1a;10年大廠數據\經營分析經驗&#xff0c;現任字節跳動數據部門負責人。 會一些的技術&#xff1a;數據分析、算法、SQL、大數據相關、python&#xff0c;歡迎探討交流 歡迎加入社區&#xff1a;碼上找工作 作者專欄每日更新&#xff1a; LeetCode解鎖1000題…

C#上位機1ms級高精度定時任務

precisiontimer 安裝擴展包 添加引用 完整代碼 using PrecisionTiming;using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; us…

WinSCP軟件出錯:連接被意外關閉了

問題描述&#xff1a; WinSCP 登錄 M3568 的 linux系統&#xff0c;提示 列出’/home/root’的目錄項時出錯&#xff0c;連接被意外關閉 具體提示如下圖所示&#xff0c;列出’/home/root’的目錄項時出錯。 連接被意外關閉了 服務器發送命令的退出狀態255 原因及解決&#xf…

notepad++安裝 hex-editor插件

打開notepad 點擊插件 搜索 hex-editor,點擊右側 安裝install 安裝成功后&#xff0c;在已安裝插件中就有顯示了

spring boot參數驗證注解@NotNull、@NotBlank和@NotEmpty區別

目錄 前言說明舉例 前言 使用spring boot參數驗證是常常會使用NotNull、NotBlank和NotEmpty三個判斷是否不為空的注解&#xff0c;中文都有不能為空的意思&#xff0c;大部分使用者都傻傻分清它們之間到底有什么區別。今天就讓咱們來一起探索它們之間的不同吧。 說明 注解名…

等保測評安全物理環境測評講解

等保測評中的安全物理環境測評主要關注信息系統的物理安全保護措施&#xff0c;確保機房、設備和數據的物理安全。以下是安全物理環境測評的關鍵點講解&#xff1a; 1. **物理位置選擇**&#xff1a; - 機房應選擇在具有防震、防風和防雨能力的建筑內。 - 應避免設在建筑…

【數據庫】數據庫指令

一。數據庫打開 1.命令行 2.進入mysql mysql -uroot -p密碼 3.退出 exit&#xff1b; 二。針對數據庫的操作 1.創建數據庫&#xff08;有分號&#xff09; create database student; 2.使用數據庫 use student 3.刪除數據庫&#xff08;有分號&#xff09; drop database…

verilog基礎語法之數據類型

verilog基礎語法之數據類型 1、 wire類型2、 reg類型3、向量 Verilog最常用的數據類型有兩種&#xff1a;線網&#xff08;wire&#xff09;和寄存器&#xff08;reg&#xff09;。其中&#xff0c;wire 類型表示硬件單元之間的物理連線&#xff0c;reg用來表示存儲單元。 1、…

數據庫調優-數據庫優化

數據庫優化 如何發現復雜的SQL有問題&#xff1f; 一個個去explain嗎&#xff1f;你有沒有這樣的困惑&#xff0c;開發代碼運行順暢絲滑&#xff0c;上生產了卻卡的一逼&#xff1f; 哈哈&#xff0c;相信大家都會遇到這樣的問題&#xff01; sql 復制代碼 # 舉個栗子&…

4. 從感知機到神經網絡

目錄 1. 從感知機到神經網絡 2. 最簡單的神經網絡 3. 激活函數的引入 1. 從感知機到神經網絡 之前章節我們了解了感知機&#xff0c;感知機可以處理與門、非與門、或門、異或門等邏輯運算&#xff1b;不過在感知機中設定權重的工作是由人工來做的&#xff0c;而設定合適的&a…

【將Maven源改為國內阿里云鏡像源】

目錄 一、如何配置Maven鏡像源&#xff1f; 二、Idea中的Maven配置 ?三、項目與你本地倉庫和中央倉庫的聯系 一、如何配置Maven鏡像源&#xff1f; 1、打開你的Maven用戶設置文件(settings.xml)。默認情況下&#xff0c;該文件存在于你的用戶目錄下的.m2文件夾中。如果你沒…

小程序內使用web-view組件嵌套H5頁面,當H5頁面更換了內容后,小程序里的h5頁面不更新

這個問題是由于小程序緩存了H5的內容造成的&#xff0c;可以在H5鏈接后面拼接個參數&#xff0c;加上時間戳可做用于H5的版本號&#xff0c;這樣每次訪問都可以全新的鏈接展示內容避免緩存&#xff0c;代碼如下wxml&#xff1a; <view> <web-view src"{{urlpath…

Kafka 執行命令超時異常: Timed out waiting for a node assignment

Kafka 執行命令超時異常&#xff1a; Timed out waiting for a node assignment 問題描述&#xff1a; 搭建了一個kafka集群環境&#xff0c;在使用命令行查看已有topic時&#xff0c;報錯如下&#xff1a; [rootlocalhost bin]# kafka-topics.sh --list --bootstrap-server…

《機器學習by周志華》學習筆記-決策樹-01

本書中的「決策樹」有時指學習方法,有時指學得的樹。 1、基本流程 1.1、概念 基本流程,亦稱「判定樹」 決策樹(decision tree),是一種常見的機器學習方法。以二分類任務為例,我們希望從給定訓練數據集學得一個模型,用以對新樣例進行分離。 以二分類任務為例,可看作對…

一圖看懂 | 藍卓煤炭行業解決方案

煤炭是我國能源保障的“壓艙石,也是國民經濟中重要的支柱產業之一無論是發電、建材、造紙、冶金、化工等工業領域都離不開煤炭近年來&#xff0c;在“雙碳”及能源安全雙重背景下推動智能化技術與煤炭產業的融合發展提升煤礦安全生產能力的重要性與日俱增智慧礦山的建設已逐漸成…

CentOS 7安裝配置docker

CentOS 7、8安裝、配置docker 這里宿主機的型號選擇是centos7.9.2009的版本 1.宿主機關閉防火墻和selinux&#xff0c;配置ipv4 #設置SELinuxdisabled vim /etc/selinux/config SELinuxdisabled 查看防火墻狀態&#xff1a;firewall-cmd --state 關閉防火墻&#xff1a;syst…