using python to post data to a form

Chris Rebert clp2 at rebertia.com
Mon Apr 4 02:24:34 EDT 2011


On Sun, Apr 3, 2011 at 10:36 PM, Littlefield, Tyler <tyler at tysdomain.com> wrote:
> Hello:
> I have some data that needs to be fed through a html form to get validated
> and processed and the like. How can I use python to send data through that
> form, given a specific url? the form says it uses post, but I"m not really
> sure what the difference is.

They're different HTTP request methods:
http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods

The key upshot in this case is that GET requests place the parameters
in the URL itself, whereas POST requests place them in the body of the
request.

> would it just be:
> http://mysite.com/bla.php?foo=bar&bar=foo?

No, that would be using GET.

> If so, how do I do that with python?

Sending POST data can be done as follows (I'm changing bar=foo to
bar=qux for greater clarity):

from urllib import urlopen, urlencode

form_data = {'foo' : 'bar', 'bar' : 'qux'}
encoded_data = urlencode(form_data)
try:
    # 2nd argument to urlopen() is the POST data to send, if any
    f = urlopen('http://mysite.com/bla.php', encoded_data)
    result = f.read()
finally:
    f.close()

Relevant docs:
http://docs.python.org/library/urllib.html

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list