Python:用urllib或urllib2点击按钮
我想用Python点击一个按钮,网页会自动填好表单的信息。发送请求的HTML代码是:
INPUT type="submit" value="Place a Bid">
我该怎么做呢? 我能仅用urllib或urllib2来点击这个按钮吗?还是说我需要使用像mechanize或twill这样的工具?
3 个回答
1
使用urllib.urlopen,你可以把表单中的值作为数据参数发送到表单标签指定的页面。不过,这样做并不会自动操作你的浏览器,所以你得先用其他方法获取表单的值。
2
你可以看看 IronWatin 这个工具 - https://github.com/rtyler/IronWatin,它可以帮助你用代码填写表单和“点击”按钮。
11
使用表单的目标属性,并将任何输入作为POST数据发送,像这样:
<form target="http://mysite.com/blah.php" method="GET">
......
......
......
<input type="text" name="in1" value="abc">
<INPUT type="submit" value="Place a Bid">
</form>
Python:
# parse the page HTML with the form to get the form target and any input names and values... (except for a submit and reset button)
# You can use XML.dom.minidom or htmlparser
# form_target gets parsed into "http://mysite.com/blah.php"
# input1_name gets parsed into "in1"
# input1_value gets parsed into "abc"
form_url = form_target + "?" + input1_name + "=" + input1_value
# form_url value is "http://mysite.com/blah.php?in1=abc"
# Then open the new URL which is the same as clicking the submit button
s = urllib2.urlopen(form_url)
你可以用 HTMLParser 来解析HTML内容。
另外,别忘了要用以下方法对任何POST数据进行编码: