Login to Twitter using requests
<p>I am trying to login to Twitter with <code>requests</code> module in Python (2.7), and after I am logged in, I want to visit another directory on Twitter.</p>

<p>So:</p>

<ol>
<li>Visit: <a href="https://twitter.com/login" rel="nofollow">https://twitter.com/login</a></li>
<li>Locate username/pass elements</li>
<li>Input Twitter Credentials</li>
<li>Visit: <a href="https://twitter.com/settings/your_twitter_data" rel="nofollow">https://twitter.com/settings/your_twitter_data</a></li>
<li>Input Twitter Password</li>
</ol>

<p>My code so far:</p>

<pre><code>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)
</code></pre>

<p>When run, this is the error I get:</p>

<pre><code>Traceback (most recent call last):
  File "twitter.py", line 10, in &lt;module&gt;
    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)
</code></pre>

<p>You are using <code>r.json()</code> though response is HTML, try <code>r.text</code> instead.</p>

<p>Also if you want to know you are successfully logged in, you'd rather check for your profile picture or something alike.</p>

<p>Then, you should use <code>requests.Session()</code>, more info there : <a href="http://docs.python-requests.org/en/master/user/advanced/" rel="nofollow">http://docs.python-requests.org/en/master/user/advanced/</a></p>

python twitter python-requests