詳解用python寫網(wǎng)絡(luò)爬蟲-爬取新浪微博評(píng)論
新浪微博需要登錄才能爬取,這里使用m.weibo.cn這個(gè)移動(dòng)端網(wǎng)站即可實(shí)現(xiàn)簡化操作,用這個(gè)訪問可以直接得到的微博id。
分析新浪微博的評(píng)論獲取方式得知,其采用動(dòng)態(tài)加載。所以使用json模塊解析json代碼
單獨(dú)編寫了字符優(yōu)化函數(shù),解決微博評(píng)論中的嘈雜干擾字符
本函數(shù)是用python寫網(wǎng)絡(luò)爬蟲的終極目的,所以采用函數(shù)化方式編寫,方便后期優(yōu)化和添加各種功能
# -*- coding:gbk -*- import re import requests import json from lxml import html #測試微博4054483400791767 comments=[] def get_page(weibo_id): url='https://m.weibo.cn/status/{}'.format(weibo_id) html=requests.get(url).text regcount=r'"comments_count": (.*?),' comments_count=re.findall(regcount,html)[-1] comments_count_number=int(comments_count) page=int(comments_count_number/10) return page-1 def opt_comment(comment): tree=html.fromstring(comment) strcom=tree.xpath('string(.)') reg1=r'回復(fù)@.*?:' reg2=r'回覆@.*?:' reg3=r'//@.*' newstr='' comment1=re.subn(reg1,newstr,strcom)[0] comment2=re.subn(reg2,newstr,comment1)[0] comment3=re.subn(reg3,newstr,comment2)[0] return comment3 def get_responses(id,page): url="https://m.weibo.cn/api/comments/show?id={}&page={}".format(id,page) response=requests.get(url) return response def get_weibo_comments(response): json_response=json.loads(response.text) for i in range(0,len(json_response['data'])): comment=opt_comment(json_response['data'][i]['text']) comments.append(comment) weibo_id=input("輸入微博id,自動(dòng)返回前5頁評(píng)論:") weibo_id=int(weibo_id) print('\n') page=get_page(weibo_id) for page in range(1,page+1): response=get_responses(weibo_id,page) get_weibo_comments(response) for com in comments: print(com) print(len(comments))
以上所述是小編給大家介紹的python爬取新浪微博評(píng)論詳解整合,希望對(duì)大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
使用pyinstaller打包PySide2程序中遇到的問題
說到打包,我們就需要用到python程序的打包工具pyinstaller了,這個(gè)包安裝簡單,使用同樣簡單,下面這篇文章主要給大家介紹了關(guān)于使用pyinstaller打包PySide2程序中遇到的問題,需要的朋友可以參考下2023-05-05Python3去除頭尾指定字符的函數(shù)strip()、lstrip()、rstrip()用法詳解
這篇文章主要介紹了Python3去除頭尾指定字符的函數(shù)strip()、lstrip()、rstrip()用法詳解,需要的朋友可以參考下2021-04-04Python基于詞頻排序?qū)崿F(xiàn)快速挖掘關(guān)鍵詞
這篇文章主要為大家詳細(xì)介紹了Python如何基于詞頻排序?qū)崿F(xiàn)快速挖掘關(guān)鍵詞功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-03-03python使用pandas處理excel文件轉(zhuǎn)為csv文件的方法示例
這篇文章主要介紹了python使用pandas處理excel文件轉(zhuǎn)為csv文件的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07Visual Studio Code搭建django項(xiàng)目的方法步驟
這篇文章主要介紹了Visual Studio Code搭建django項(xiàng)目的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09python __init__與 __new__的區(qū)別
本文主要介紹了python __init__與 __new__的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02Matlab讀取excel并利用拉依達(dá)準(zhǔn)則篩選數(shù)據(jù)的全過程
在Excel中錄入好數(shù)據(jù)以后經(jīng)常需要被matlab讀取,具體該如何讀取并進(jìn)行篩選呢?下面這篇文章就來給大家介紹了關(guān)于Matlab讀取excel并利用拉依達(dá)準(zhǔn)則篩選數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2021-08-08