我最近开始研究Python中的请求模块,并遇到了使用data={something}
将数据发送到网站的POST方法。因此,我很好奇,并尝试将帖子发送到google.com,想看看结果如何,例如我想搜索'hello'
。我总是遇到405
错误。我想知道为什么会收到此错误,甚至还可以将POST请求发送到用户必须填写一些数据的任何网站吗?
我知道我也可以使用GET
,但是我特别想使用POST。
我在下面使用了这段代码。
import requests
data={'q':'hello'}
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0'}
p_resp=requests.post('https://www.google.com/',headers=headers,data=data)
print(p_resp.text)
我得到一个405 error The request method POST is inappropriate for the URL
。
答案 0 :(得分:0)
实际上,如果要在Google
中进行搜索,则需要使用GET
方法而不是POST
。
这是一个搜索单词hello
的示例:
import requests
url = 'https://www.google.com/complete/search'
req = requests.get(url, params={'pql': 'hello'})
print(req.status_code)
输出:
200
但是,如果您使用POST
方法,您将拥有:
req = requests.post(url, params={'pql': 'hello'})
print(req.status_code)
输出:
405
如果您搜索状态代码200
和405
有什么区别,您会看到:
The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET : The resource has been fetched and is transmitted in the message body.
和
The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response status code indicates that the request method is known by the server but is not supported by the target resource.
因此,在这种情况下,您需要具有另一个支持POST
方法的目标才能进行测试。一个简单的目标是您自己的支持POST
的本地服务器。
有关更多详细信息,请参见here