【问题标题】:XPATH expression to count number of input tags in html formXPATH 表达式以 html 形式计算输入标签的数量
【发布时间】: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

【问题讨论】:

  • 你的&lt;input type="submit"&gt;不应该是&lt;input type="submit"/&gt;吗?

标签: python-3.x selenium-webdriver xpath


【解决方案1】:

最好使用当前form中的relative XPath定位器和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)}')

演示:

更多信息:

【讨论】:

  • 我试图在 OP 的修改后的 html 上运行它(其中第二种形式是封闭的 div 标签),但仍然得到同样的错误。你能试试吗?
  • 谢谢@Dmitri,这真的很有帮助。它不仅解决了我的问题,而且使代码简单美观。爱它。只是想知道为什么当第二种形式包含在 Div 中时我的代码不起作用。
猜你喜欢
  • 2014-01-03
  • 2018-05-19
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多