- 账号准备
- 环境准备
- 测试
账号准备
- 首先需要在twitter官方注册twitter账号,并新建一个应用,链接:新建应用
- 如果新建应用不成功,国内大多数情况都是无法验证手机号,可以参考这个教程,亲测有效,链接:验证手机号
- 注册成功后,可以查看自己的keys and access token,如下图:
环境准备
- 安装python
- 安装pip:
进入命令行,把目录切换到python的安装目录下的Script文件夹下,运行 easy_inatall pip - 安装tweepy:
在命令行中输入:pip install tweepy
测试
测试代码如下:
# -*- coding: utf-8 -*-
import tweepy
from tweepy import OAuthHandler
consumer_key = 'replace your own account consumer_key'
consumer_secret = 'replace your own account consumer_secret'
access_token = 'replace your own account access_token'
access_secret = 'replace your own account access_secret'
auth = OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_secret)
api = tweepy.API(auth)
for status in tweepy.Cursor(api.home_timeline).items(2):
print (status.text)
但是这样可能会报错,报错信息如下:
tweepy.error.TweepError: Failed to send request: HTTPSConnectionPool(host='api.twitter.com', port=443): Max retries exceeded with url: /1.1/statuses/home_timeline.json (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x0000000002FC6E80>: Failed to establish a new connection: [Errno 10061] ',)))
主要原因就是twitter被墙了,twitter的api当然也被墙了。
这时候就需要挂代理翻墙了,我使用的是自己搭建的shadowsockets。其它翻墙软件或者服务器网上有很多,请自行查找。
代理打开了之后,在原代码中,将
api = tweepy.API(auth)
改为
api = tweepy.API(auth,proxy="127.0.0.1:1080")
测试结果:成功获取了两条内容