Python Beautiful Soup 表单输入解析
我的目标是获取一个所有输入框的名称和对应值的列表。然后把它们配对起来,提交表单。输入框的名称和值是随机的。
from bs4 import BeautifulSoup # parsing
html = """
<html>
<head id="Head1"><title>Title Page</title></head>
<body>
<form id="formS" action="login.asp?dx=" method="post">
<input type=hidden name=qw1NWJOJi/E8IyqHSHA== value='gDcZHY+nV' >
<input type=hidden name=sfqwWJOJi/E8DFDHSHB== value='kgDcZHY+n' >
<input type=hidden name=Jsfqw1NdddfDDSDKKSL== value='rNg4pUhnV' >
</form>
</body>
</html>
"""
html_proc = BeautifulSoup(html)
这一部分运行得很好:
print html_proc.find("input", value=True)["value"]
> gDcZHY+nV
但是接下来的这些语句要么不工作,要么没有达到预期效果:
print html_proc.find("input", name=True)["name"]
> TypeError: find() got multiple values for keyword argument 'name'
print html_proc.findAll("input", value=True, attrs={'value'})
> []
print html_proc.findAll('input', value=True)
> <input name="qw1NWJOJi/E8IyqHSHA==" type="hidden" value="gDcZHY+nV">
> <input name="sfqwWJOJi/E8DFDHSHB==" type="hidden" value="kgDcZHY+n">
> <input name="Jsfqw1NdddfDDSDKKSL==" type="hidden" value="rNg4pUhnV">
> </input></input></input>, <input name="sfqwWJOJi/E8DFDHSHB==" type="hidden"
> value="kgDcZHY+n">
> <input name="Jsfqw1NdddfDDSDKKSL==" type="hidden" value="rNg4pUhnV">
> </input></input>, <input name="Jsfqw1NdddfDDSDKKSL==" type="hidden" value="rNg4p
> UhnV"></input>
2 个回答
7
d = {e['name']: e.get('value', '') for e in html_proc.find_all('input', {'name': True})}
print(d)
输出:
{'sfqwWJOJi/E8DFDHSHB==': 'kgDcZHY+n',
'qw1NWJOJi/E8IyqHSHA==': 'gDcZHY+nV',
'Jsfqw1NdddfDDSDKKSL==': 'rNg4pUhnV'}
在@alecxe的基础上,这个方法避免了出现KeyErrors,并将表单解析成一个字典,这样更方便用于requests库。
url = 'http://example.com/' + html_proc.form['action']
requests.post(url , data=d)
不过,如果情况变得更复杂(比如涉及到cookies或脚本),你可能需要使用Mechanize库。
出现TypeError的原因是对find()方法第一个参数'名称'的理解有误。应该用html_proc.find("input", attrs={'name': True})
。另外,在attrs参数中,应该用字典{'value': True}
,而不是集合{'value'}。
23
你不能用 BeautifulSoup
提交一个表单,但我可以告诉你怎么获取名字和值的配对列表:
print [(element['name'], element['value']) for element in html_proc.find_all('input')]
输出结果是:
[('qw1NWJOJi/E8IyqHSHA==', 'gDcZHY+nV'),
('sfqwWJOJi/E8DFDHSHB==', 'kgDcZHY+n'),
('Jsfqw1NdddfDDSDKKSL==', 'rNg4pUhnV')]