Script to automate Twitter OAuth login

This is my first post. I don't know how to use Qiita.

I had the opportunity to write a test for Twitter's OAuth login without using a browser, so I will take out only the parts that can be generalized and leave it. However, I am thinking because it is a problem that I can not determine whether it is an error of the Twitter API or an error of the function under test.

twitteroauth.py


# -*- coding: utf-8 -*-
 
import mechanize
import cookielib
 
 
class TwitterWebOAuth(object):
    """Twitter Web OAuth"""
 
    def __init__(self, username, password, is_cookie=False):
        self._is_cookie = is_cookie
        self._username = username
        self._password = password
 
    def oauth(self, oauth_url, callback_proc):
        """OAuth with twitter account"""
        br = self._browser()
        br.open(oauth_url)
        self._login_with_twitter(br)
        url = br.geturl()
        return callback_proc(url, br)
 
    def patch(self, proc):
        """patch script using Browser"""
        self._browser()
        return proc()
 
    def _browser(self):
        br = mechanize.Browser()
        br.set_handle_equiv(True)
        br.set_handle_redirect(True)
        br.set_handle_referer(True)
        br.set_handle_robots(False)
        if self._is_cookie:
            cj = cookielib.CookieJar()
            br.set_cookiejar(cj)
        return br
 
    def _login_with_twitter(self, br):
        url = br.geturl()
        br.open(url)
        br.select_form(nr=0)
        br.form['session[username_or_email]'] = self._username
        br.form['session[password]'] = self._password
        br.submit()

Example

Let's log in to Qiita and open your own settings screen. Don't forget pip install mechanize.

test.py


# -*- coding: utf-8 -*-

from twitteroauth import TwitterWebOAuth


def callback(url, br):
    br.open('https://qiita.com/settings/profile')
    url = br.geturl()
    print url
    #I thought I'd do something on the settings screen, but it's getting messy


if __name__ == '__main__':
    to = TwitterWebOAuth('naoiwata', 'xxxxxx', True)
    to.oauth(
        'https://qiita.com/auth/twitter',
        callback
    )

When I run the file, it outputs https://qiita.com/settings/profile, so it seems that I logged in and opened my profile setting screen.

Recommended Posts

Script to automate Twitter OAuth login
Twitter OAuth with Django
Attempt to automate Pricone R
Try to analyze Twitter trends
Post to Twitter using Python
I tried to automate everything including Google OAuth with two-step verification