首页 > 解决方案 > 如何使用 Selenium WebDriver 和 Autohotkey 获取 HTML 中的元素总数?

问题描述

我正在尝试按给定类获取 HTML 页面中的项目总数。我正在使用 Selenium 和 Autohotkey 来做到这一点

我已经搜索了很多这个主题,但没有找到我的特定解决方案

我研究的大多数建议和答案都包括解决方案,但针对 Java 或其他语言,而不是针对 Autohotkey(尽管在这种情况下它们具有相似的结构)

使用此代码处理:

<html>
    <body>
        <div id="pancakes">
            <button class="button">Blueberry</button><br><br>
            <button class="button">Banana</button><br><br>
            <button class="button">Strawberry</button><br><br>
            <button class="button">Yumi</button><br><br>
        </div>
    </body>
</html>

要按类从元素中获取文本,可以通过以下方式完成:

driver.findElementByClass("button").Attribute("innerText")

输出:蓝莓

现在,对于使用 Xpath 获取某个类的某个项目,如下所示:

driver.findElementsByXpath("//*[contains(@id,'pancakes')]/button").item[1].Attribute("innerText") 

输出:草莓

我需要的是获得“按钮”的总数。所以我需要一个给我“ 4 ”的输出(因为有4个“按钮”

我还没有找到在 Autohotkey 中执行此操作的方法。我见过其他语言的解决方案,比如

一种

len(driver.find_elements_by_xpath('//a'))

WebElement webElement = driver.findElement(By.xpath("//form[@id='form1']/div[4]"));

//Get list of table elements using tagName
List<WebElement> list = webElement.findElements(By.tagName("table"));

C

IList<IWebElement> selectElements = driver.FindElements(By.TagName("select"));

foreach (IWebElement select in selectElements)
{
    var selectElement = new SelectElement(select);
    Console.WriteLine(selectElement.SelectedOption.Text);
}

还有更多,但这不适用于 Autohokey,因为这些函数和变量(如 len()、IList 等)

我希望以任何可能的方式获得项目总数

我正在考虑我尚未创建的 Selenium 的一些功能,我不知道(比如一些 - 在行尾 - “.len”,“.size”,“.count”,但没有一个有效为了我)

欢迎和赞赏任何建议,谢谢!

编辑:哇,我只是错过了“ .Count ”上的“ ()

这就是我要找的

driver.findElementsByXpath("//*[contains(@id,'pancakes')]/button").Count()

感谢 supputuri

标签: javascriptseleniumautohotkey

解决方案


您可以使用Count()方法来获取与您的 xpath 匹配的元素数量。

 driver.findElementsByXpath("//*[contains(@id,'pancakes')]/button").Count()

您可以参考this了解更多信息。


推荐阅读