在您的情况下,仅使用类名是不够的。
By.cssSelector(".ban")有15个匹配节点By.cssSelector(".hot")有11个匹配节点By.cssSelector(".ban.hot")有5个匹配节点
因此,您需要更多限制来缩小范围。下面的 选项1和2 可用于CSS选择器,其中1可能是最适合您的需求的选择器。
选项1:使用列表项的索引(CssSelector或XPath)
局限性
- 如果站点的结构发生变化,则不够稳定
例:
driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5"));driver.FindElement(By.XPath("//*[@id='rightbar']/ul/li[3]/h5"));选项2:使用Selenium的FindElements
,然后对其进行索引。(CssSelector或XPath)
局限性
- 如果站点的结构发生变化,则不够稳定
- 不是本机选择器的方式
例:
// note that By.CssSelector(".ban.hot") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your caseIList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(".ban.hot"));IWebElement banUsStates = hotBanners[3];选项3:使用文字(仅XPath)
局限性
- 不适用于多语言网站
- 仅用于XPath,不适用于Selenium的CssSelector
例:
driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']"));选项4:索引分组的选择器(仅XPath)
局限性
- 如果站点的结构发生变化,则不够稳定
- 仅用于XPath,不用于CssSelector
例:
driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]"));选项5:通过href找到隐藏的列表项链接,然后遍历到h5(仅XPath)
局限性
- 仅用于XPath,不用于CssSelector
- 效能低下
- 棘手的XPath
例:
driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, 'geo.craigslist.org/iso/us/al')]]/h5"));


