Reputation: 25
I have recently started studying about the requests module in Python and came across the POST method of sending data to websites using data={something}
.So, I was curious and tried sending a post to google.com and wanted to see what I get back as a result like if I want to search 'hello'
. I always get a 405
error.I wanted to know why I get this error and is there even a way to send a POST request to any website where the user has to fill some data?
I am aware that I can also use GET
but I specifically want to use POST.
I used this code below.
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)
I get a 405 error The request method POST is inappropriate for the URL
.
Upvotes: 1
Views: 4107
Reputation: 9257
Actually if you want to search in Google
you need to use GET
method instead of POST
.
Here is an example to search the word hello
:
import requests
url = 'https://www.google.com/complete/search'
req = requests.get(url, params={'pql': 'hello'})
print(req.status_code)
output:
200
However if you use the POST
method you'll have:
req = requests.post(url, params={'pql': 'hello'})
print(req.status_code)
output:
405
And if you search what's the difference between 200
and 405
status codes, you'll see that:
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.
And
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.
So, in this case you need to have another target that supports POST
method in order to do your tests. A trivial target is your own local server that supports POST
.
For more details see here
Upvotes: 1