用Python爬取美團(tuán)外賣APP評論

一、介紹

朋友暑假實踐需要美團(tuán)外賣APP評論這一份數(shù)據(jù),一開始我想,這不就抓取網(wǎng)頁源代碼再從中提取數(shù)據(jù)就可以了嗎,結(jié)果發(fā)現(xiàn)事實并非如此,情況和之前崔大講過的分析Ajax來抓取今日頭條街拍美圖類似,都是通過異步加載的方式傳輸數(shù)據(jù),不同的是這次的是通過JS傳輸,其他的基本思路基本一致,希望那些數(shù)據(jù)能幫到她吧

二、流程

  • 目標(biāo)站點分析
    用瀏覽器打開美團(tuán)外賣APP評論,F(xiàn)12
    1.首先我們要找到我們想要的評論數(shù)據(jù),在第一次“失敗”的直接抓取網(wǎng)頁源代碼后,我們發(fā)現(xiàn)它是通過Ajax加載的,我們點擊JS選項,可以發(fā)現(xiàn)JS項目里面的返回結(jié)果有我們想要的數(shù)據(jù),勾選Preserve log,當(dāng)點擊查看更多評論時,后臺(JS里)會出現(xiàn)新的Ajax請求,發(fā)現(xiàn)還有參數(shù)start和的變化,其他請求參數(shù)不變,start的參數(shù)變化是以10遞增的,的參數(shù)變化可就讓人摸不著頭腦(這個時候我們也不要方,因為大多情況下沒有規(guī)律的參數(shù)都是沒用的)
    1.0

2.經(jīng)過我們對http://comment.mobilem.#/comment/getComments?callback=jQuery17203361018749253357_1503362214558&baike=%E7%BE%8E%E5%9B%A2%E5%A4%96%E5%8D%96+Android_com.sankuai.meituan.takeoutnew&c=message&a=getmessage&start=0&count=10&_=1503362215647進(jìn)行分析后發(fā)現(xiàn)它的標(biāo)準(zhǔn)式為‘http://comment.mobilem.#/comment/getComments?&baike=%E7%BE%8E%E5%9B%A2%E5%A4%96%E5%8D%96+Android_com.sankuai.meituan.takeoutnew&start=’+str(i*10),i每次增加1,就包含新的十條評論的內(nèi)容,所以我們通過改變i的值就可以拿到不同的數(shù)據(jù)

2.0

  • 分析url的網(wǎng)頁源代碼,在源代碼里有我們想要的評論數(shù)據(jù),我們可以用正則(在這里正則還是比較好用的)把我們想要的信息弄下來

  • 開啟循環(huán),批量抓取

  • 保存數(shù)據(jù)至文本和數(shù)據(jù)庫

---------------------------17/8/26第一次更新:關(guān)于獲取評論的編碼問題
#之前是這樣處理的:
def parse_one_page(html):
    pattern2 = re.compile('"m_type":"0",(.*?),"username"', re.S)
    items=re.findall(pattern2,html)
    for item in items:
        item = "{" + item + "}"
        item=json.loads(item)
        write_to_file(item)
        print(item)
        save_to_mongo(item)

#皮皮哥告訴了我他的獨家正則匹配方法可以匹配出來,這樣的確獲得的item沒有編碼問題
def parse_one_page(html):
    pattern = '\"content\":\".*?"'
    items=re.findall(pattern,html)
    for item in items:
        item =eval(item.split(':',1)[1])
        write_to_file(item)
        print(item)
        save_to_mongo(item)

#對一般正則寫法獲得的item進(jìn)行的方法,這是從皮皮哥那里得知的,親測有效
def parse_one_page(html):
    pattern = re.compile('rsion_name".*?"content":(.*?),"username"', re.S)
    items=re.findall(pattern,html)
    #print(items)
    for item in items:
        item = item.encode('utf-8').decode('unicode_escape')
        write_to_file(item)
        print(item)
        save_to_mongo(item)

三、代碼

#config.py
MONGO_URL='localhost'
MONGO_DB='meituan'
MONGO_TABLE='meituan'
import requests
from requests.exceptions import RequestException
import json
import re
from day31.config import *
import pymongo

client=pymongo.MongoClient(MONGO_URL)
db=client[MONGO_DB]
base_url='http://comment.mobilem.#/comment/getComments?callback=jQuery17209056727722758744_1502991196139&baike=%E7%BE%8E%E5%9B%A2%E5%A4%96%E5%8D%96+Android_com.sankuai.meituan.takeoutnew&start='

def the_url(url):
    try:
        response = requests.get(url)
        if response.status_code==200:
            response.encoding='utf-8'
            return response.text
        return None
    except RequestException:
        print('請求出錯')
        return None

def the_total():
    html=the_url(base_url)
    pattern1 = re.compile('"total":(.*?),"messages"', re.S)
    Total = re.findall(pattern1, html)
    Total=int(':'.join(Total))
    #print(type(Total))
    show='總計評論%d條'%Total
    print(show)
    write_to_file(show)
    return Total

def parse_one_page(html):
    pattern2 = re.compile('"m_type":"0",(.*?),"username"', re.S)
    items=re.findall(pattern2,html)
    for item in items:
        item = "{" + item + "}"
        item=json.loads(item)
        write_to_file(item)
        print(item)
        save_to_mongo(item)



def save_to_mongo(result):
    try:
        if db[MONGO_TABLE].insert(result):
            print('儲存到MongoDB成功',result)
    except Exception:
        print('儲存到MongoDB失敗',result)

def write_to_file(content):
    with open('meituan_result.text','a',encoding='utf-8') as f:
        f.write(json.dumps(content,ensure_ascii=False)+'\n')
        f.close()

def main():
    Total=the_total()
    Total=int(Total/10)+2
    for i in range(Total):
        url = base_url + str(i*10)
        if the_url(url)!=None:
            html=the_url(url)
            parse_one_page(html)
        else:
            print('輸完啦')
    ps='PS:因為有些評論空,所以實際評論比抓取的少'   #這是我瞎猜的
    write_to_file(ps)
    print(ps)

if __name__ == '__main__':
    main()

四、最后得到的數(shù)據(jù)視圖和文件

3.0

五、總結(jié)

1.程序報錯很正常,不要一報錯就問別人,先自己思考、百度
2.在數(shù)據(jù)類型處理方面的知識還要加強(qiáng)
3.感謝皮皮哥、感謝姚文峰前輩!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容