Tweepy1_抓取Twitter数据

之前一直想用爬虫登陆并抓取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://stackoverflow.com/questions/13729638/how-can-i-filter-emoji-characters-from-my-input-so-i-can-save-in-mysql-5-5

 
http://tweepy.readthedocs.io/en/v3.5.0/getting_started.html

Tweepy 3.5.0 Doc (1) Getting started

开始

简介

如果你是第一次接触Tweepy,就请从这里开始。这个教程的目标是提供你学习Tweepy所需的信息,让你学习完本教程后能熟练使用Tweepy。我们在这主要谈论重要的基础内容,而不会涉及太多细节,


你好 Tweepy

[python] view plain copy
  1. import tweepy  
  2.   
  3. auth = tweepy.OAuthHandler(consumer_key, consumer_secret)  
  4. auth.set_access_token(access_token, access_token_secret)  
  5.   
  6. api = tweepy.API(auth)  
  7.   
  8. public_tweets = api.home_timeline()  
  9. for tweet in public_tweets:  
  10.     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:

[python] view plain copy
  1. # Get the User object for twitter...  
  2. user = api.get_user('twitter')  


Model中包含了数据和一些有用的方法:

[python] view plain copy
  1. print user.screen_name  
  2. print user.followers_count  
  3. for friend in user.friends():  
  4.    print friend.screen_name  

更多内容请参见 ModelsReference(链接)


 
原文地址:https://www.cnblogs.com/webRobot/p/6281556.html