【问题标题】:selenium very similar xpaths?硒非常相似的xpaths?
【发布时间】:2023-03-11 23:29:01
【问题描述】:

我在一个页面上有两个按钮,它们的 xpath 非常相似 -

我试图点击的按钮 -

/html/body/div[@id='wrapper']/div[@id='content']/div[@id='contentarea']/div[@id='votecontent']/div[@id='votetext']/div[@id='voteboxes']/div[@id='votenow'][2]/form/input[2]

我试图忽略另一个按钮 -

/html/body/div[@id='wrapper']/div[@id='content']/div[@id='contentarea']/div[@id='votecontent']/div[@id='votetext']/div[@id='voteboxes']/div[@id='votenow'][1]/form/input[2]

两者之间的唯一区别是

[@id='votenow'][1]

[@id='votenow'][2]

但我不知道如何与拥有 votenow[2] 的人互动,无论我采取哪种方式,它似乎总是与第一个互动,因为这是它找到的第一个

这适用于使用 firefox 驱动程序的 java,任何建议都会很棒:)

【问题讨论】:

  • 你能把 id="voteboxes" 的 html 代码贴出来吗?

标签: java selenium xpath selenium-webdriver


【解决方案1】:

只需找到它们并通过索引获取所需的一个:

List<WebElement> buttons = driver.findElements(By.xpath("your xpath"));
WebElement secondButton = buttons.get(1);

【讨论】:

    【解决方案2】:

    首先

    请与您的开发人员交谈!将相同的 id 分配给同一页面上的两个不同元素(在您的情况下为按钮)是 非常糟糕的做法!它让 DEV 和 QA 的工作变得不必要地困难!

    第二

    您发布的 xpath 表达式已经包含这两个按钮之间的区别。所以你只需要找到第一个并点击它。

    通过 xpath:

    您可以使用 xpath - 应该足以搜索带有id="votenow" 的元素。如前所述,在这种情况下,您可以非常精确,并且已经过滤了第二个按钮:

    WebElement button02 = driver.findElement(By.xpath("//div[@id='votenow'][2]/form/input[2]"));
    button02.click();
    

    通过 id:

    正如@alecxe 已经指出的那样,您也可以先对几个元素进行更一般的搜索,然后过滤掉正确的元素。在这种情况下,我个人会使用 id:

    List<WebElement> buttonWrappers = driver.findElements(By.id("votenow"));
    
    // you want the button-input-element in the 2nd wrapper element, indexing starts at 0, so do this:
    WebElement button02 = buttonWrappers.get(1).findElement(By.xpath("//input[2]"));
    // since it seems there are several input elements below the desired div, you can use xpath again
    

    【讨论】:

    • 这不仅仅是一种非常糟糕的做法,the HTML spec 定义了页面上的 id 必须是唯一的......但我经常看到它。
    猜你喜欢
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多