【问题标题】:Accessing a element in selenium访问 selenium 中的元素
【发布时间】:2017-05-16 15:12:19
【问题描述】:

在 Firebug 中,我有一个包含此内容的链接:

<a id="fwMainContentForm:j_idt156:2:selectRole" class="cb_or_somename cb_area_0219" onclick="jsf.util.chain(this,event,'$(this).attr(\'disabled\', \'disabled\');return true;','mojarra.jsfcljs(document.getElementById(\'fwMainContentForm\'),{\'fwMainContentForm:j_idt156:2:selectRole\':\'fwMainContentForm:j_idt156:2:selectRole\'},\'\')');return false" href="#">Somename</a>

如何使用“类名”访问链接(点击)?

我尝试了以下方法:

   WebElement rolle = driver.findElement(By.className("cb_or_somename cb_area_0219"));

但我得到了错误:

线程“main”中的异常
org.openqa.selenium.InvalidSelectorException:给定的选择器 cb_or_somename cb_area_0219 无效或不会生成 WebElement。
发生以下错误: InvalidSelectorError:不允许复合类名

【问题讨论】:

    标签: selenium xpath selenium-webdriver css-selectors


    【解决方案1】:

    cb_or_somename cb_area_0219 实际上是两个类。 By.className可以收到其中一个

    WebElement rolle = driver.findElement(By.className("cb_or_somename"));
    // or
    WebElement rolle = driver.findElement(By.className("cb_area_0219"));
    

    如果你想同时定位元素,请使用cssSelector

    WebElement rolle = driver.findElement(By.cssSelector(".cb_or_somename.cb_area_0219"));
    

    【讨论】:

    • 好的,但是我可以告诉 Selenium 将它们都用于一个 web 元素吗?
    • @MagnusJensen 使用cssSelector,在我的回答中。
    • 我做到了,但得到了错误:线程“主”org.openqa.selenium.WebDriverException 中的异常:元素在点(181.5、10.216659545898438)处不可点击。其他元素会收到点击:

      命令持续时间或超时:61 毫秒
    • @MagnusJensen 你有一个覆盖按钮的横幅或弹出窗口,你需要先关闭它。看看stackoverflow.com/questions/27608921/…
    • 奇怪,因为我没有看到弹出窗口。试过 driver.switchTo().parentFrame();和 driver.switchTo().defaukltFrame();就在调用 WebElement 之前......但没有运气
    【解决方案2】:

    要使用这两个类查找元素,您可以使用 xpath 而不是 className。

     WebElement rolle = driver.findElement(By.xpath("//*[contains(@class,'cb_or_somename cb_area_0219')]"));
    

    【讨论】:

      猜你喜欢
      • 2020-01-14
      • 2012-02-08
      • 2016-04-05
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      • 2011-12-28
      相关资源
      最近更新 更多