简体   繁体   English

机械化无法在Google Appengine中自动进行Gmail登录

[英]Mechanize not working for automating gmail login in Google Appengine

I have used mechanize and deployed an app on GAE and it works fine. 我已经使用机械化并在GAE上部署了一个应用程序,并且运行良好。 But, for an app that I am making, I am trying to automate login to gmail through mechanize. 但是,对于我正在制作的应用程序,我正在尝试通过机械化自动登录gmail。 It doesn't work in the development environment on local machine as well as after deploying on appengine. 在本地计算机上的开发环境中以及在appengine上部署后,它均不起作用。

I have been able to use the same script to run it on my server through mod_python using PSP. 我已经能够使用同一脚本通过PSP通过mod_python在服务器上运行它。

I found a lot of solutions here, but none of them seem to work for me. 我在这里找到了很多解决方案,但是似乎没有一个对我有用。 Here is a snippet of my code: 这是我的代码片段:

<snip>
br = mechanize.Browser()
response = br.open("http://www.gmail.com")
loginForm = br.forms().next()
loginForm["Email"] = self.request.get('user')
loginForm["Passwd"] = self.request.get('password')
response = br.open(loginForm.click())
response2 = br.open("http://mail.google.com/mail/h/")
result = response2.read()
<snip>

When I look at the result, all I get is the login page when used with appengine. 当我查看结果时,与appengine一起使用时,得到的只是登录页面。 But with mod_python hosted on my own server, I get the page with the user's inbox. 但是将mod_python托管在我自己的服务器上后,我得到了带有用户收件箱的页面。

The problem is most likely due to how Google crippled the urllib2 module on GAE. 该问题最有可能是由于Google如何削弱GAE上的urllib2模块。

Internally it now uses the urlfetch module (which is something that Google wrote) and they have completely removed the HTTPCookieProcessor() functionality - meaning, cookies are NOT persisted from request to request which is the critical piece when automatically logging into sites programmatically. 现在,它内部使用urlfetch模块(这是Google编写的),并且它们已经完全删除了HTTPCookieProcessor()功能-这意味着,cookie不会在请求之间持久存在,这在以编程方式自动登录网站时是至关重要的。

There is a way around this, but not using mechanize. 有一种解决方法,但不使用机械化。 You have to roll your own Cookie processor - here is the basic approach I took (not perfect, but it gets the job done): 您必须使用自己的Cookie处理器-这是我采用的基本方法(虽然不完美,但可以完成工作):

import urllib, urllib2, Cookie
from google.appengine.api import urlfetch
from urlparse import urljoin
import logging

class GAEOpener(object):
    def __init__(self):
        self.cookie = Cookie.SimpleCookie()
        self.last_response = None

    def open(self, url, data = None):
        base_url = url
        if data is None:
            method = urlfetch.GET
        else:
            method = urlfetch.POST
        while url is not None:
            self.last_response = urlfetch.fetch(url = url,
                payload = data,
                method = method,
                headers = self._get_headers(self.cookie),
                allow_truncated = False,
                follow_redirects = False,
                deadline = 10
                )
            data = None # Next request will be a get, so no need to send the data again. 
            method = urlfetch.GET
            self.cookie.load(self.last_response.headers.get('set-cookie', '')) # Load the cookies from the response
            url = urljoin(base_url, self.last_response.headers.get('location'))
            if url == base_url:
                url = None
        return self.last_response

    def _get_headers(self, cookie):
        headers = {
            'Host' : '<ENTER HOST NAME HERE>',
            'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)',
            'Cookie' : self._make_cookie_header(cookie)
             }
        return headers

    def _make_cookie_header(self, cookie):
        cookie_header = ""
        for value in cookie.values():
            cookie_header += "%s=%s; " % (value.key, value.value)
        return cookie_header

    def get_cookie_header(self):
        return self._make_cookie_header(self.cookie)

You can use it like you would urllib2.urlopen, except the method you would use is just "open". 您可以像使用urllib2.urlopen一样使用它,只是要使用的方法只是“打开”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM