为什么我在使用urllib2请求URL时得到“HTTP错误405:方法不允许”?

时间:2022-09-04 08:01:57

I am using urllib2 and urllib libraries in python

我正在python中使用urllib2和urllib库

suppose i had the following code

假设我有以下代码

import urllib2
import urllib

url = 'http://ah.example.com'
half_url = u'/servlet/av/jd?ai=782&ji=2624743&sn=I'

req = urllib2.Request(url, half_url.encode('utf-8'))
response = urllib2.urlopen(req)
print response

when i run the above code i am getting the following error

当我运行上述代码时,我将得到以下错误

Traceback (most recent call last):
  File "example.py", line 39, in <module>
    response = urllib2.urlopen(req)
  File "/usr/lib64/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib64/python2.7/urllib2.py", line 398, in open
    response = meth(req, response)
  File "/usr/lib64/python2.7/urllib2.py", line 511, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib64/python2.7/urllib2.py", line 436, in error
    return self._call_chain(*args)
  File "/usr/lib64/python2.7/urllib2.py", line 370, in _call_chain
    result = func(*args)
  File "/usr/lib64/python2.7/urllib2.py", line 519, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 405: Method Not Allowed

can anyone let me know whats happening here and why its not working

谁能告诉我这里发生了什么,为什么不工作

Thanks in advance............

提前谢谢............

1 个解决方案

#1


13  

The server you are calling is telling you that the POST method is not allowed for the URL you are trying to call.

您正在调用的服务器告诉您,不允许您试图调用的URL使用POST方法。

By passing in the path portion of your URL as the Request object data parameter you are making this a POST instead of a GET.

通过将URL的path部分作为请求对象数据参数传递给您,您将使其成为一个POST而不是GET。

I suspect you wanted to send a GET request instead:

我怀疑你想发送一个GET请求代替:

req = urllib2.Request(url + half_url.encode('utf-8'))

#1


13  

The server you are calling is telling you that the POST method is not allowed for the URL you are trying to call.

您正在调用的服务器告诉您,不允许您试图调用的URL使用POST方法。

By passing in the path portion of your URL as the Request object data parameter you are making this a POST instead of a GET.

通过将URL的path部分作为请求对象数据参数传递给您,您将使其成为一个POST而不是GET。

I suspect you wanted to send a GET request instead:

我怀疑你想发送一个GET请求代替:

req = urllib2.Request(url + half_url.encode('utf-8'))