Python爬取新浪微博實操

第一步:選擇從手機端爬取

新浪微博手機端地址:https://m.weibo.cn/
登錄自己的微博賬號。

第二步:爬取劉亦菲的微博爲例:

2.1獲取需要爬取微博的Request_URL,以及構造網絡請求的User_Agent和Cookies:

右鍵-檢查,刷新網頁,Network,size排序,
其中Request_URL就是我們需要爬取微博的請求地址,如圖:
在這裏插入圖片描述
User_Agent和Cookies:
在這裏插入圖片描述

2.2點擊Preview,微博的信息存儲在card_type=9的列表中,

譬如劉亦菲的這條微博:
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

第三步:具體的代碼如下:

import requests
from bs4 import BeautifulSoup
import json
import re
import time

#1:使用正則表達之去除html標籤
def filter_tags(htmlstr):
#先過濾CDATA
    re_cdata=re.compile('//<!\[CDATA\[[^>]*//\]\]>',re.I) #匹配CDATA
    re_script=re.compile('<\s*script[^>]*>[^<]*<\s*/\s*script\s*>',re.I)#Script
    re_style=re.compile('<\s*style[^>]*>[^<]*<\s*/\s*style\s*>',re.I)#style
    re_br=re.compile('<br\s*?/?>')#處理換行
    re_h=re.compile('</?\w+[^>]*>')#HTML標籤
    re_comment=re.compile('<!--[^>]*-->')#HTML註釋
    s=re_cdata.sub('',htmlstr)#去掉CDATA
    s=re_script.sub('',s) #去掉SCRIPT
    s=re_style.sub('',s)#去掉style
    s=re_br.sub('\n',s)#將br轉換爲換行
    s=re_h.sub('',s) #去掉HTML 標籤
    s=re_comment.sub('',s)#去掉HTML註釋
    s=s.replace('網頁鏈接','')
    return s


headers = {'user-agent':
          '自行補充'
          }
          
cookies = {'cookies':
           '自行補充'
          }

url_1 = input ( "請輸入微博博主的url:" + str() ) 


i = 1
count = 1
while True:
    url = url_1 + '&page=' + str(i)
    req = requests.get(url, headers=headers, cookies=cookies)
    text = req.text
    try:
        content = json.loads(text).get('data')
        cards = content.get('cards')  
        if (len(cards)>0):
            for j in range(len(cards)):
                card_type = cards[j].get('card_type')
                if (card_type == 9):
                    mblog = cards[j].get('mblog')
                    attitudes_count=mblog.get('attitudes_count')
                    comments_count=mblog.get('comments_count')
                    created_at=mblog.get('created_at')
                    reposts_count=mblog.get('reposts_count')
                    scheme=cards[j].get('scheme')
                    text1=mblog.get('text')
                    text2=filter_tags(text1)
                    print ( str(count) + "\n"+"發佈時間:"+str(created_at)+"\n"+"微博內容:"+text2+"\n")
                    count = count + 1
            i = i + 1
            time.sleep(5)
        else:
            break 
    except Exception as e:
        print (e)
        pass    

第四:執行上段代碼:

在這裏插入圖片描述
程序比較粗糙,僅做新手練習。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章