【问题标题】:How to click on this button with Selenium but the id is not unique如何使用 Selenium 单击此按钮,但 id 不是唯一的
【发布时间】:2017-11-16 07:11:06
【问题描述】:
<button value="1" class="_42ft _4jy0 layerConfirm uiOverlayButton _4jy3 _4jy1 selected _51sy" type="submit">Confirm</button>

以上是 Facebook 页面上一个按钮的 html 代码。我想帮助 selenium web 驱动程序点击这个按钮,但标签的 id 每次刷新都会改变

Code on facebook website

感谢大家的帮助,但在大家的帮助和反复试验的帮助下,我已经解决了这个问题。

【问题讨论】:

  • 这个按钮标签中的id在哪里?
  • id 来自代码中的上一行,每次页面刷新时都会更改
  • 如果需要可以通过文字找到按钮page_button = browser.find_element(By.XPATH, "//button[text()='Confirm']").click()
  • 您可以使用submit()提交form,无需点击按钮
  • @Thomas 感谢您的解决方案,但无法识别文本,我之前也尝试过

标签: selenium


【解决方案1】:

使用ExplicitWait 直到您的元素可见,然后执行点击

WebDriverWait wait = new WebDriverWait(driver,60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//button[@type='submit'][normalize-space()='Confirm']")));

driver.findElement(By.xpath("//button[@type='submit'][normalize-space()='Confirm']")).click();

另一种解决方案是,如果某些 javascript 阻止您单击按钮,然后使用下面的 JavascriptExecutor 代码,如果有任何问题,请告诉我

WebElement button = driver.findElement(By.xpath("//button[@type='submit'][normalize-space()='Confirm']"));
 JavascriptExecutor js = (JavascriptExecutor)driver;    
 js.executeScript("arguments[0].click();", button);

【讨论】:

  • 谢谢,但我找到了另一种更简单的方法来解决我的问题。
【解决方案2】:

您可以为您的案例使用以下 xpath:

driver.findElement(By.xpath("//*[contains(text(),'Confirm')]")).click();

希望对你有所帮助。

【讨论】:

    【解决方案3】:

    由于 Facebook 元素的 class 和 id 是动态的,因此使用 Selenium 进一步自动化会遇到麻烦。

    在这种情况下,您可以使用 xpath

    //button[@type='submit' and text()='Confirm']
    

    //button[text()='Confirm']
    

    【讨论】:

      【解决方案4】:

      您可以为此使用固定的类名

      driver.findElement(By.className("layerConfirm"));
      

      或组合

      driver.findElement(By.cssSelector(".layerConfirm.uiOverlayButton"));
      

      如果动态id有固定部分,可以使用部分id

      // id=someid134313
      driver.findElement(By.cssSelector("[id*='someid']"));
      

      或通过“确认”文本

      driver.findElement(By.xpath("//button[contains(., 'Confirm')]"));
      

      【讨论】:

      • 在最后一个中,当我使用 .Click() 操作时,它说元素不可见
      猜你喜欢
      • 2019-06-10
      • 2019-12-14
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多