python - 使用请求登录 Twitter

标签 python twitter python-requests

我正在尝试使用 Python (2.7) 中的 requests 模块登录 Twitter,登录后我想访问 Twitter 上的另一个目录。

所以:

  1. 访问:https://twitter.com/login
  2. 找到用户名/密码元素
  3. 输入 Twitter 凭据
  4. 访问:https://twitter.com/settings/your_twitter_data
  5. 输入 Twitter 密码

到目前为止我的代码:

import requests
import sys
import os

#LOGIN
data = {"session[username_or_email]":"MY_USERNAME",
    "session[password]":"MY_PASSWORD"}
r = requests.post("https://twitter.com/login/", data=data)

if ("success" in r.json()):
    print "Logged in successfully!"
else:
    print "Failed to login!"
    sys.exit(0)

#CHANGE URL AND INPUT PASSWORD
data = {"auth_password":"MY_PASSWORD"}
r = requests.post("https://twitter.com/settings/your_twitter_data", data=data)

if ("success" in r.json()):
    print "Success!"
    sys.exit(0)

运行时,这是我收到的错误:

Traceback (most recent call last):
  File "twitter.py", line 10, in <module>
    if ("success" in r.json()):
  File "/usr/lib/python2.7/dist-packages/requests/models.py", line 808, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 516, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 373, in decode
    raise JSONDecodeError("Extra data", s, end, len(s))
simplejson.scanner.JSONDecodeError: Extra data: line 1 column 5 - line 1 column 81 (char 4 - 80)

最佳答案

尽管响应是 HTML,但您正在使用 r.json(),请尝试使用 r.text

此外,如果您想知道自己是否已成功登录,您最好检查您的个人资料图片或类似内容。

然后,您应该使用 requests.Session(),更多信息如下:http://docs.python-requests.org/en/master/user/advanced/

关于python - 使用请求登录 Twitter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39150015/

相关文章:

python - json.decoder.JSONDecodeError : Expecting value: line 1 column 1 (char 0) python

python - 在 python 中设置全局套接字超时的正确方法是什么?

python - 求减IPSet

python - 使用 python 抓取 Udacity 网站?

python - 我可以在 string.format 方法中使用 for 循环吗?

java - 使用 Scribe 构建 oauth 登录

python - 请求,绑定(bind)到一个ip

python - 为什么这个 python 列表需要这么多内存?

python - 如何在没有 Oauth 的情况下登录 twitter 脚本?

支持 update_with_media 的 Node.js Twitter 库