Submitting form with python

2019-08-12 17:36发布

I need to parse HTML in my python script. However to get to the page I need, in my browser, to click radio button and submit form. So, how can I submit form with python and get rendered html back? Thanks, I would appreciate any help.

The form I'm talking about:

<form id="ac" method="post">
      <input type="radio" id="a" name="a" value="2" onchange="document.getElementById('ac').submit();" checked="checked">
      <input type="radio" id="aa" name="a" value="1" onchange="document.getElementById('ac').submit();">
      <input type="radio" id="aaa" name="a" value="0" onchange="document.getElementById('ac').submit();">
</form>

1条回答
乱世女痞
2楼-- · 2019-08-12 18:04

You can use urllib for this: http://docs.python.org/2.7/library/urllib.html

A radio button sends its data as name=value, in this case a=2.

Modified example from Python URLLib / URLLib2 POST :

import urllib
import httplib

server='myserver.com'
get_data='/link/with/get/data.php?test=1'

data = urllib.urlencode({'a': 2})
h = httplib.HTTPConnection('enfenion.com')
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
h.request('POST', get_data, data, headers)
r = h.getresponse()
print r.read()
查看更多
登录 后发表回答