Mohsin Anees
Mohsin Anees

Reputation: 698

How to send request to a website through POST request?

My purpose is to write a python script which returns the facebook ID when a url is given as input. I found this website which does the same thing.

I want to ask:

1) Is it possible that I send a POST request myself which will include the url entered by user using "urllib" library "urlopen" command? And then extract the answer from urllib.read() function?

2) If not possible, how can I do this task?

I have little idea about POST and HTTP. But can't figure this out.

From reading the page source, the POST request is being sent this way:

<form method="POST">
    <div class="form-group">
        <input
            name="url"
            type="text"
            placeholder="https://www.facebook.com/YourProfileName"
            class="input-lg form-control">
        </input>

    </div>
    <button type="submit" class="btn btn-primary">Find numeric ID &rarr;</button>

</form>

Upvotes: 1

Views: 1839

Answers (1)

GhaziBenDahmane
GhaziBenDahmane

Reputation: 548

Well the easiest answer would be for you to use requests
you can install it using

pip install requests

the normal usage would be ( assuming you're using python 3) :

import requests
payload={
    'key1':'value1',
    'key2':'value2'
}
r = requests.post('http://url', data = payload)
print(r.content)

If you want to use urllib you can use this sample code found here

import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' }

data = urllib.parse.urlencode(values)
data = data.encode('ascii') # data should be bytes
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
   the_page = response.read()

Upvotes: 4

Related Questions