Can't automate login using python mechanize (m

2019-07-24 04:21发布

问题:

I seem to have difficulty logging into a website, which requires browser authenticaton. What happens is when you first log on, the website redirects you to a page saying "We have sent an email to your email, click on the link to authenticate this browser."

I'm using the mechanize module for python. The page would log in, however the website never recognizes the "browser" hence many "Please register this browser" emails! I tried giving custom headers as well as adding a cookie handler as per other examples... no luck. The website thinks the script is a new (unauthorized) browser each time I visit.

Init code looks like this:

    self.br = mechanize.Browser( factory=mechanize.RobustFactory() )
    self.br.add_handler(PrettifyHandler())

    cj = cookielib.LWPCookieJar()
    self.br.set_cookiejar(cj)

    self.br.addheaders = [('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
                          ('User-agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.17 (KHTML, like Gecko) Ubuntu Chromium/24.0.1312.56 Chrome/24.0.1312.56 Safari/537.17'),
                          ('Referer', 'https://www.temp.com/logout'),
                          ('Accept-Encoding', 'gzip,deflate,sdch'),
                          ('Accept-Language', 'en-GB,en-US;q=0.8,en;q=0.6'),
                          ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'),
                          ]

And my login code looks like this. It fills in a simple html form and submits it.

    self.br.open('https://www.temp.com/login')

    # Select the first (index zero) form
    self.br.select_form(nr=0)

    # User credentials
    self.br.form['username'] = 'temp'
    self.br.form['password'] = 'temp'

    # Login
    self.br.submit()

    # Inventory
    body = self.br.response().read().split('\n')

And yet everytime I get this email : "To activate your browser, please click on the following link..." even after I follow the link and activate/authenticate the browser.

回答1:

If you want to save session, try to save cookies with save/load function. Example:

cj = cookielib.LWPCookieJar()
cj.save('cookies.txt', ignore_discard=False, ignore_expires=False)
...
cj.load('cookies.txt', ignore_discard=False, ignore_expires=False)