【问题标题】:How can I tell between these two buttons in Selenium?如何区分 Selenium 中的这两个按钮?
【发布时间】:2016-06-12 02:58:49
【问题描述】:

我在 Python 上运行 Selenium,但我不知道如何区分这些按钮,以便我可以使用 Selenium 单击一个。我需要点击选项 1。我不知道如何从中获取任何重要的数据标签,但我对此非常陌生!

<tbody>
    <tr>
        <td>TOP1                                 </td>
        <td>11/16/15</td>
        <td>12/30/99</td>
        <td>Balance due on account</td>
        <td><button onclick="addNotify('RANDOMNUMBERS','option_1    ','Option1                                 ','IDNUMBER');">Add Alert</button></td>
    </tr>
    <tr>
        <td>TOP2                                        </td>
        <td>11/16/15</td>
        <td>12/30/99</td>
        <td>Balance due on account</td>
        <td><button onclick="addNotify('RANDOMNUMBERS','option_2   ','Option2                                        ','IDNUMBER');">Add Alert</button></td>
    </tr>
</tbody>

我需要点击 TOP1 后面的按钮的“添加警报”

我已经尝试了所有这些(个人)以及更多,但无法为我工作:

driver.find_element_by_xpath("//button[@title='Add Hold']").click()
driver.find_element_by_tag_name("button").click()
driver.find_element_by_xpath("//div[@class='button' and contains(text(), 'Add Alert')]").click()
driver.find_element_by_xpath("//*[@class=\"button\"]/descendant::span[text()='option_1    ']").click()

【问题讨论】:

  • 你能用代码本身而不是截图来编辑这个问题吗?
  • 那里,我修好了。

标签: python html selenium


【解决方案1】:

选项 1、3 和 4 不起作用,因为它们不是正确的 xpath(您没有 title 属性,button 不是类,option_1 不是按钮的一部分文本);选项 2 将返回第一个元素,因此它应该适用于页面上的第一个按钮,但通常最好更具体。

如果按钮的文本不同(它不在您的 HTML 代码中,但我不确定它是不是拼写错误),则使用:

//button[contains(text(),'Add Alert')]

否则使用

//button[contains(@onclick,'option_1')]

如果在 find 中使用时这两个 xpath 都失败了:

driver.find_element_by_xpath(...).click()

那么你需要检查两件事:

  1. 这种形式是否在某种 iframe 中?如果是,你需要switch to iframe才能找到它

  2. 也有可能是按钮没有立即出现,需要wait才能解决:

    wait = WebDriverWait(driver, 10)
    element = wait.until(EC.element_to_be_clickable((By.XPATH,"<same xpath as above>")))
    element.click()
    

【讨论】:

  • '//button[contains(@onclick,'option_1')]' 工作,谢谢!我在放@value,我没有意识到@是html标签!
【解决方案2】:

你尝试的那些与标记中的不匹配,首先你需要为你的按钮添加类,如果你要 yung @class。

但是你做的还是错的,如果这个表是动态的,你需要使用 List 来获取表的行。首先为表格行和按钮添加类:

<!-- Add class to your <tr> -->
<tr class="rows">
<!-- and class to you <button> -->
<button class="button" onclick="addNotify('RANDOMNUMBERS','option_1    ','Option1                                 ','IDNUMBER');">Add Alert</button>

用途:

List<WebElement> buttons = driver.findElements(By.cssSelector(".rows"));
//Since you wanted the first button after TOP 1 use get index 0 (get(0))
buttons.get(0).findElement(By.xpath("//button[@class='button']")).click();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2019-09-21
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多