我想计算HTML表单中存在的输入标签的数量。
我已将Selenium Web驱动程序(Chrome)与Python3结合使用。
Python代码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def extract_login_details(url):
options = Options()
options.add_argument('--headless')
browser = webdriver.Chrome(chrome_options=options)
browser.get(url)
forms = browser.find_elements_by_xpath('//form')
print(f'forms - {len(forms)}')
for i in range(len(forms)):
inputs = browser.find_elements_by_xpath(f'//form[{i+1}]//*/input | //form[{i+1}]/input')
print(f'input tags in form{i+1} is {len(inputs)}')
extract_login_details('http://localhost:8081/selenium/test2.jsp')
test2.jsp
<html>
<body>
<form action="form1" method="post" autocomplete="on" >
<input type="email" class="inputtext" name="email1" id="email1"/>
<input type="password" class="inputtext" name="pass" id="pass"/>
<input type="submit">
</form>
<form action="form2">
<input type="email" class="inputtext" name="email2" id="email2"/>
<div><input type="password" class="inputtext" name="pass2" id="pass2"/></div>
</form>
</body>
</html>
正确的输出
表格-2
form1中的输入标签为3
form2中的输入标签为2
但是当我将第二个表格放在div标签(修改后的test2.jsp )中时,输出错误。
<html>
<body>
<form action="form1" method="post" autocomplete="on" >
<input type="email" class="inputtext" name="email1" id="email1"/>
<input type="password" class="inputtext" name="pass" id="pass"/>
<input type="submit">
</form>
<div>
<form action="form2">
<input type="email" class="inputtext" name="email2" id="email2"/>
<div><input type="password" class="inputtext" name="pass2" id="pass2"/></div>
</form>
</div>
</body>
</html>
错误的输出
表格-2
form1中的输入标签为5
form2中的输入标签为0
答案 0 :(得分:1)
最好将当前relative XPath中的form
定位符与descendant轴一起使用,以收集属于当前表单的所有嵌套input
元素
inputs =forms[i].find_elements_by_xpath("./descendant::input")
完整代码以防万一:
forms = driver.find_elements_by_xpath("//form")
print(f'forms - {len(forms)}')
for i in range(len(forms)):
inputs =forms[i].find_elements_by_xpath("./descendant::input")
print(f'input tags in form{i + 1} is {len(inputs)}')
演示:
更多信息: