python爬取新浪微博內容

來源:互聯網
上載者:User
用Python編寫爬蟲,爬取微博大V的微博內容,本文以女神的微博為例(爬新浪m站:https://m.weibo.cn/u/1259110474)

一般做爬蟲爬取網站,首選的都是m站,其次是wap站,最後考慮PC站。當然,這不是絕對的,有的時候PC站的資訊最全,而你又恰好需要全部的資訊,那麼PC站是你的首選。一般m站都以m開頭後接網域名稱, 所以本文開搞的網址就是 m.weibo.cn。

前期準備
1.代理IP
網上有很多免費代理ip,如西刺免費代理IPhttp://www.xicidaili.com/,自己可找一個可以使用的進行測試;
2.抓包分析
通過抓包擷取微博內容地址,這裡不再細說,不明白的小夥伴可以自行百度尋找相關資料,下面直接上完整的代碼

完整代碼:

# -*- coding: utf-8 -*-import urllib.requestimport json#定義要爬取的微博大V的微博IDid='1259110474'#設定代理IPproxy_addr="122.241.72.191:808"#定義頁面開啟函數def use_proxy(url,proxy_addr):    req=urllib.request.Request(url)    req.add_header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0")    proxy=urllib.request.ProxyHandler({'http':proxy_addr})    opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)    urllib.request.install_opener(opener)    data=urllib.request.urlopen(req).read().decode('utf-8','ignore')    return data#擷取微博首頁的containerid,爬取微博內容時需要此iddef get_containerid(url):    data=use_proxy(url,proxy_addr)    content=json.loads(data).get('data')    for data in content.get('tabsInfo').get('tabs'):        if(data.get('tab_type')=='weibo'):            containerid=data.get('containerid')    return containerid#擷取微博大V帳號的使用者基本資料,如:微博暱稱、微博地址、微博頭像、關注人數、粉絲數、性別、等級等def get_userInfo(id):    url='https://m.weibo.cn/api/container/getIndex?type=uid&value='+id    data=use_proxy(url,proxy_addr)    content=json.loads(data).get('data')    profile_image_url=content.get('userInfo').get('profile_image_url')    description=content.get('userInfo').get('description')    profile_url=content.get('userInfo').get('profile_url')    verified=content.get('userInfo').get('verified')    guanzhu=content.get('userInfo').get('follow_count')    name=content.get('userInfo').get('screen_name')    fensi=content.get('userInfo').get('followers_count')    gender=content.get('userInfo').get('gender')    urank=content.get('userInfo').get('urank')    print("微博暱稱:"+name+"\n"+"微博首頁地址:"+profile_url+"\n"+"微博頭像地址:"+profile_image_url+"\n"+"是否認證:"+str(verified)+"\n"+"微博說明:"+description+"\n"+"關注人數:"+str(guanzhu)+"\n"+"粉絲數:"+str(fensi)+"\n"+"性別:"+gender+"\n"+"微博等級:"+str(urank)+"\n")#擷取微博內容資訊,並儲存到文本中,內容包括:每條微博的內容、微博詳情頁面地址、點贊數、評論數、轉寄數等def get_weibo(id,file):    i=1    while True:        url='https://m.weibo.cn/api/container/getIndex?type=uid&value='+id        weibo_url='https://m.weibo.cn/api/container/getIndex?type=uid&value='+id+'&containerid='+get_containerid(url)+'&page='+str(i)        try:            data=use_proxy(weibo_url,proxy_addr)            content=json.loads(data).get('data')            cards=content.get('cards')            if(len(cards)>0):                for j in range(len(cards)):                    print("-----正在爬取第"+str(i)+"頁,第"+str(j)+"條微博------")                    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')                        text=mblog.get('text')                        with open(file,'a',encoding='utf-8') as fh:                            fh.write("----第"+str(i)+"頁,第"+str(j)+"條微博----"+"\n")                            fh.write("微博地址:"+str(scheme)+"\n"+"發布時間:"+str(created_at)+"\n"+"微博內容:"+text+"\n"+"點贊數:"+str(attitudes_count)+"\n"+"評論數:"+str(comments_count)+"\n"+"轉寄數:"+str(reposts_count)+"\n")                i+=1            else:                break        except Exception as e:            print(e)            passif __name__=="__main__":    file=id+".txt"    get_userInfo(id)    get_weibo(id,file)

爬取結果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.