不支持复合类名考虑搜索一个类名并过滤结果

问题描述

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

假设您有这样的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

解决方法

我正在使用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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...