【发布时间】:2019-07-11 19:00:48
【问题描述】:
我想计算 HTML 表单中存在的输入标签的数量。
我在 Python3 中使用过 Selenium Web Driver (Chrome)。
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 标签中时(modified 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
【问题讨论】:
-
你的
<input type="submit">不应该是<input type="submit"/>吗?
标签: python-3.x selenium-webdriver xpath