python爬取景点信息_python 爬取马蜂窝景点翻页文字评论的实现
使用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的值就行)。
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'評論.*?\n.*?(.*?)'
date_list = re.compile(date_pattern).findall(page)
#星級列表
star_pattern = r''
star_list = re.compile(star_pattern).findall(page)
#評論列表
comment_pattern = r'
([\s\S]*?)
'comment_list = re.compile(comment_pattern).findall(page)
for num in range(0, len(date_list)):
#日期
date = date_list[num]
#星級評分
star = star_list[num]
#評論內容,處理一些標簽和符號
comment = comment_list[num]
comment = str(comment).replace('?', '')
comment = comment.replace('
', '')
comment = comment.replace('
', '')
print(date+"\t"+star+"\t"+comment)
else:
print("爬取失敗")
結果
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持聚米學院。
總結
以上是生活随笔為你收集整理的python爬取景点信息_python 爬取马蜂窝景点翻页文字评论的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 宋紫薇评暴雪CEO说腾讯和字节是最好的公
- 下一篇: 曾靠“疫情红利”崛起的 Zoom,不能再