本文實例講述了Python實現的爬取網易動態評論操作。分享給大家供大家參考,具體如下:
打開網易的一條新聞的源代碼后,發現并沒有所要得評論內容。
經過學習后發現,源代碼只是一個完整頁面的“骨架”,而我所需要的內容是它的填充物,這時候需要打開工具里面的開發人員工具,從加載的“骨肉”里找到我所要的評論
圈住的是類型
找到之后打開網頁,發現json類型的格式,用我已學過的正則,bs都不好鬧,于是便去了解了正則,發現把json的格式換化成python的格式后,用列表提取內容是一條明朗的道路。。。
但是在細致分析的時候也發現了問題
從這里獲得每條評論時,感覺有點不對,觀察發現如果是回復評論的評論會出現他回復那條評論的數據,于是用正則提取了一下
最終的代碼如下:
#coding=utf-8__author__ = 'kongmengfan123'import urllibimport reimport jsonimport timedef gethothtml(url):#最熱評論 page=urllib.urlopen(url) html=page.read() get_json(html)def gethnewtml():#最新評論有5頁 for i in range(1,6): url = 'http://comment.news.163.com/api/v1/products/a2869674571f77b5a0867c3d71db5856/threads/C4QFIJNS0001875O/comments/newList?offset=%d&limit=30&showLevelThreshold=72&headLimit=1&tailLimit=2&callback=getData&ibc=newspc&_=1478010624978'%i*30 page = urllib.urlopen(url) html=page.read() time.sleep(1) get_json(html)def get_json(json_): end_=re.compile(r'/);')#將json網頁轉化成python數據 begain=re.compile(r'getData/(') json_=begain.sub('',json_) json_=end_.sub('',json_) ajson=json.loads(json_) lis=ajson["commentIds"]#獲得每條評論的鍵 n=0 for i in range(1,len(lis)): try: xulie=re.compile('/d{10,}')#取得準確評論的鍵(去掉回復) bia=re.findall(xulie,lis[n]) w.write(ajson['comments'][bia[len(bia)-1]]['user']['nickname'].encode('utf-8')+'|') except KeyError: w.write(ajson['comments'][bia[len(bia)-1]]['user']['location'].encode('utf-8')+'|') if (len(lis[n])>13): xulie=re.compile('/d{10,}') bia=re.findall(xulie,lis[n]) w.write(ajson['comments'][bia[len(bia)-1]]['content'].encode('utf-8')+'/n') else: w.write(ajson['comments'][lis[n]]['content'].encode('utf-8')+'/n') n=n+1 return lisw=open('wangyi.txt','w')w.write('用戶名'+'|'+'熱門評論'+'/n')hot_=gethothtml('http://comment.news.163.com/api/v1/products/a2869674571f77b5a0867c3d71db5856/threads/C4QFIJNS0001875O/comments/hotList?offset=0&limit=40&showLevelThreshold=72&headLimit=1&tailLimit=2&callback=getData&ibc=newspc')w.write('用戶名'+'|'+'最新評論'+'/n')gethnewtml()w.close()
成功。
更多關于Python相關內容可查看本站專題:《Python Socket編程技巧總結》、《Python正則表達式用法總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
新聞熱點
疑難解答