栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

需要通过CSS在selenium中找到元素

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

需要通过CSS在selenium中找到元素

在您的情况下,仅使用类名是不够的。

  • 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"));


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/403719.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号