python機器學習-乳腺癌細胞挖掘(博主親自錄制視頻)https://study.163.com/course/introduction.htm?courseId=1005269003&utm_campaign=commission&utm_source=cp-400000000398149&utm_medium=share
之前一直想用爬蟲登陸並抓取twitter數據,試過scrapy,requests等包,都沒成功,可能是我還不太熟悉的原因,不過
今天發現了一個新包tweepy,專門用於在Python中處理twitter API。先嘗試一下教程的第一個例子,經過了自己的一點修改
代碼如下:
Tweepy抓取twitter數據 1 import re import tweepy auth = tweepy.OAuthHandler("xxxxx", "xxxxx") auth.set_access_token("xxxxx", "xxxxx") api = tweepy.API(auth) highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]') public_tweets = api.home_timeline() num = 0 for tweet in public_tweets: print num num += 1 text_noem = highpoints.sub('--emoji--', tweet.text) text_noem = text_noem.encode('utf8')
代碼解釋:
第3-4行:導入tweepy和re模塊。之所以這么簡單的代碼中要用re是因為在提取推文過程中遇到了emoji表情,而emoji unicode是無法編碼成 gbk 的,所以要用正則表達式把所有表情都替換掉。
第6-9行:設置API和token,這個需要注冊后在apps.twitter.com新建application后獲得。
第11行:根據auth返回API對象,用於具體返回responses
第14行:設置emoji表情的正則表達式,用於過濾出所有的表情,此處參考了下面注明的一篇stackoverflow文章。
第15行:獲取用戶時間線上的信息
第16行:設置一個計數的變量
第17行:遍歷所有的推文:
循環內:
第18-22行:輸出序號,並輸出推文內容,將所有的emoji unicode用 ’--emoji--‘ 替代並將unicode編碼為utf8以解決不能輸出的問題。
抓取Twitter數據的重點是twitter要求所有requets都必須經過OAuth認證,而tweepy這個包在這方面的設定讓authentication變得十分方便。
http://tweepy.readthedocs.io/en/v3.5.0/getting_started.html
Tweepy 3.5.0 Doc (1) Getting started
開始
簡介
如果你是第一次接觸Tweepy,就請從這里開始。這個教程的目標是提供你學習Tweepy所需的信息,讓你學習完本教程后能熟練使用Tweepy。我們在這主要談論重要的基礎內容,而不會涉及太多細節,
你好 Tweepy
- import tweepy
- auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
- auth.set_access_token(access_token, access_token_secret)
- api = tweepy.API(auth)
- public_tweets = api.home_timeline()
- for tweet in public_tweets:
- print tweet.text
這 個例子可以下載你Twitter主頁上的推文,並且把相應的文本內容打印到控制台。Twitter要求所有請求(requests)都通過OAuth協議 進行授權(身份認證)。Authentication Tutorial(身份認證教程)(鏈接)中有授權的詳細介紹。
API
API類為Twitter的所以REST API方法提供接口(The API class provides access to the entire twitter RESTful API methods.)每種方法接受不同的參數,但是都返回response。更多請參見API Reference(鏈接)
模型
當我們使用一種API方法時,我們大多數情況下會得到一個Tweepy model 類實例,其中包含了從Twitter返回的可以讓我們應用到app中的數據。比如下面這行代碼就返回了一個User model:
- # Get the User object for twitter...
- user = api.get_user('twitter')
Model中包含了數據和一些有用的方法:
- print user.screen_name
- print user.followers_count
- for friend in user.friends():
- print friend.screen_name
更多內容請參見 ModelsReference(鏈接)