使用Chrome、python3.7、requests庫和VSCode進行爬取馬蜂窩黃鶴樓的文字評論(http://www.mafengwo.cn/poi/5426285.html)。
首先,我們復制一段評論,查看網頁源代碼,按Ctrl+F查找,發現沒有找到評論,說明評論內容不在http://www.mafengwo.cn/poi/5426285.html頁面。
回到頁面,劃到評論列表,右鍵檢查,選擇Network,然后點擊后一頁翻頁,觀察Network里的變化,我們要爬的文件就在下面的某個文件里(主要找XHR和JS兩個模塊)。選擇Preview可以更好的讓我們尋找我們想要的文件,然后選擇Headers找到我們要爬的url。
經過分析我們找到要爬取的url是http://pagelet.mafengwo.cn/poi/pagelet/poiCommentListApi?callback=jQuery18102698237405245767_1579401525334¶ms=%7B%22poi_id%22%3A%225426285%22%2C%22page%22%3A2%2C%22just_comment%22%3A1%7D&_ts=1579402072160&sn=20e98d65a0&=1579402072161
然而點進去是這樣的
這個時候對比一下這兩個頁面的Request Headers,發現原頁面多了個Refer參數
原頁面
然后看一下請求get請求需要的參數Query String Parameters,其中poi_id是景點id,page是評論頁面(翻頁只用改變page的值就行)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
import re import time import requests #評論內容所在的url,?后面是get請求需要的參數內容 comment_url = 'http://pagelet.mafengwo.cn/poi/pagelet/poiCommentListApi?' requests_headers = { 'Referer' : 'http://www.mafengwo.cn/poi/5426285.html' , 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36' } #請求頭 for num in range ( 1 , 6 ): requests_data = { 'params' : '{"poi_id":"5426285","page":"%d","just_comment":1}' % (num) #經過測試只需要用params參數就能爬取內容 } response = requests.get(url = comment_url,headers = requests_headers,params = requests_data) if 200 = = response.status_code: page = response.content.decode( 'unicode-escape' , 'ignore' ).encode( 'utf-8' , 'ignore' ).decode( 'utf-8' ) #爬取頁面并且解碼 page = page.replace( '\\/' , '/' ) #將\/轉換成/ #日期列表 date_pattern = r '<a class="btn-comment _j_comment" id="codetool">
結果
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。 原文鏈接:https://blog.csdn.net/qq_45373920/article/details/104037607 延伸 · 閱讀
精彩推薦
|