Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Submit a form and get response

Tags:

python

My general question : How could i submit a form and then get response from website with a python program ?

My specific : I want to send some thing like Ajax XHR send to a web file and get response from it , problematically .

  • I don't want to use any browser and do it in the code like this link.

  • I have read this articles and they just make me confused and can't find good documented about it.

like image 278
Golix Avatar asked Apr 27 '13 08:04

Golix


2 Answers

Requests is very easy too!

Here is the example from their homepage pertaining to POSTing forms

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print r.text
{
 ...
"form": {
"key2": "value2",
"key1": "value1"
   },
  ...
}
like image 57
Nipun Batra Avatar answered Nov 01 '22 21:11

Nipun Batra


Simply use urllib2

import urllib
import urllib2 

data = {
    'field1': 'value1',
    'field2': 'value2',
}

req = urllib2.Request(url="http://some_url/...",
                      data=urllib.urlencode(data), 
                      headers={"Content-type": "application/x-www-form-urlencoded"}) 
response = urllib2.urlopen(req)
the_page = response.read()
like image 22
onon15 Avatar answered Nov 01 '22 21:11

onon15