使用Python的urllib2 POST在虚拟机环境中我做错了什么?

时间:2012-02-15 23:46:47

标签: python urllib2 python-2.7

import urllib
import urllib2
from urllib2 import Request

url = 'https://www.google.com'
response = urllib2.urlopen(url)

login_url = (url + '/login')
data = {'email': 'john',
        'password': 'example'}
req = Request(login_url, urllib.urlencode(data))
response = urllib2.urlopen(req)


  File "test.py", line 50, in <module>
    response = urllib2.urlopen(req)
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 400, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
  urllib2.HTTPError: HTTP Error 405: Method Not Allowed

我正在做一个POST方法。这个脚本适用于运行python 2.7.1的MAC OSX,但是,在运行python 2.7的虚拟机上,它会抛出该错误。在发出POST请求时,是否有一些我认为会传递的HTTPHeader?

2 个答案:

答案 0 :(得分:1)

你应该在这里找到你需要的文档:

http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html

要进行身份验证,您需要使用此网址https://www.google.com/accounts/ClientLogin,该网址需要您尝试访问的服务,并且会为您指定的服务提供access_token

您需要为此类请求存储Cookie:

import urllib2
import cookielib
cookiejar = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
urllib2.install_opener(opener)
return urllib2

答案 1 :(得分:0)

是的,对于Google,他们可能会要求您有一个共同的用户代理才能登录。 除此之外,您还需要存储他们在python中提供的cookie。你可以使用CookieJar。

这是一个很棒的教程,可以教你如何为你的请求发送标题和保存cookie。 http://www.voidspace.org.uk/python/articles/urllib2.shtml

http://www.voidspace.org.uk/python/articles/cookielib.shtml