我正在使用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>
不,就您的问题而言,您自己的答案并不是最好的答案。
假设您有这样的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")),但是就像您在问题中说的那样,这将不起作用,因为您需要另一种通过复合类名称查找元素的方法。
driver.FindElement(By.ClassName("bighead"))
div
driver.FindElement(By.ClassName("bighead crb"))
这就是为什么大多数人使用功能更强大By.CssSelector或By.XPath。然后您有:
By.CssSelector
By.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