【问题标题】:Compound class names are not supported. Consider searching for one class name and filtering the results不支持复合类名。考虑搜索一个类名并过滤结果
【发布时间】:2013-12-09 12:07:08
【问题描述】:

我正在使用 driver.findelement by.classname 方法读取 Firefox 浏览器上的元素,但我收到“不支持复合类名。考虑搜索一个类名并过滤结果。”异常

这是我的代码

driver.FindElement(By.ClassName("bighead crb")).Text.Trim().ToString()

//and here is how the html of browser looks like

<form action="#" id="aspnetForm" onsubmit="return false;">
    <section id="lx-home" style="margin-bottom:50px;">
  <div class="bigbanner">
    <div class="splash mc">
      <div class="bighead crb">LEAD DELIVERY MADE EASY</div>
    </div>
  </div>
 </section>
</form>

【问题讨论】:

    标签: c# selenium webdriver selenium-webdriver


    【解决方案1】:

    不,就您的问题而言,您自己的答案并不是最好的。

    想象一下你有这样的 HTML:

    <div class="bighead ght">LEAD DELIVERY MADE HARD</div>
    <div class="bighead crb">LEAD DELIVERY MADE EASY</div>
    

    driver.FindElement(By.ClassName("bighead")) 将找到两者并返回第一个 div,而不是您想要的。您真正想要的是 driver.FindElement(By.ClassName("bighead crb")) 之类的东西,但就像您在问题中所说的那样,这不起作用,因为您需要另一种方法来通过复合类名称查找元素。

    这就是为什么大多数人使用更强大的By.CssSelectorBy.XPath。那么你有:

    CssSelector(最好的):

    driver.FindElement(By.CssSelector(".bighead.crb")); // flexible, match "bighead small crb", "bighead crb", "crb bighead", etc.
    driver.FindElement(By.CssSelector("[class*='bighead crb']")); // order matters, match class contains  "bighead crb"
    driver.FindElement(By.CssSelector("[class='bighead crb']")); // match "bighead crb" strictly
    

    XPath(更好):

    driver.FindElement(By.XPath(".//*[contains(@class, 'bighead') and contains(@class, 'crb')]")); // flexible, match "bighead small crb", "bighead crb", "crb bighead", etc.
    driver.FindElement(By.XPath(".//*[contains(@class, 'bighead crb')]")); // order matters, match class contains string "bighead crb" only
    driver.FindElement(By.XPath(".//*[@class='bighead crb']")); // match class with string "bighead crb" strictly
    

    【讨论】:

    • CSS 选择器绝对是实现这一目标的方式。它们非常强大。
    • @user1177636 感谢您提供此示例。我一定会很快在我的自动化测试脚本中实现它。
    • 我尝试同时实现 CssSelector 和 XPath。由于某种原因,CssSelector 无法找到该元素,但 XPath 有效。我想我会继续使用 XPath。谢谢您的帮助! :)
    【解决方案2】:

    想通了这个问题,你必须搜索:

    driver.FindElement(By.ClassName("bighead")).Text.Trim().ToString(); //instead of 
    driver.FindElement(By.ClassName("bighead crb")).Text.Trim().ToString();
    

    html 类中的任何空格都代表一个新的类名,所以只需按第一个单词搜索。

    【讨论】:

    • 更好的方法是使用 CSS 选择器,这就是它们最初的用途。
    • @Arran 你能举个例子在这种情况下如何使用css选择器吗?我想摆脱使用 id 和类名
    猜你喜欢
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    相关资源
    最近更新 更多