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

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

这是我的代码

driver.FindElement(By.ClassName("bighead crb")).Text.Trim().ToString() //and here is how the html of browser looks like 
LEAD DELIVERY MADE EASY

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

想象一下你有这样的HTML:

 
LEAD DELIVERY MADE HARD
LEAD DELIVERY MADE EASY

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("bighead")).Text.Trim().ToString(); //instead of driver.FindElement(By.ClassName("bighead crb")).Text.Trim().ToString(); 

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