需要通过 css 在 selenium 中找到元素 [英] Need to find element in selenium by css

查看:35
本文介绍了需要通过 css 在 selenium 中找到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在<h5>中找到这个链接的元素us states".我正在 craigslist 中尝试这个.任何帮助将不胜感激

I want to find the element of this link "us states" in <h5>. I am trying this in craigslist. Any help will be highly appreciated

这是网址:http://auburn.craigslist.org/

 <html class="">
<head>
<body class="homepage w1024 list">
    <script type="text/javascript">
    <article id="pagecontainer">
            <section class="body">
        <table id="container" cellspacing="0" cellpadding="0" 
    <tbody>
           <tr>
    <td id="leftbar">
    <td id="center">
    <td id="rightbar">
        <ul class="menu collapsible">
            <li class="expand s">
            <li class="s">
            <li class="s">
                <h5 class="ban hot">us states</h5>
                <ul class="acitem" style="display: none;">
            </li>
        <li class="s">
        <li class="s">

推荐答案

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

Only using class names is not sufficient in your case.

  • By.cssSelector(".ban") 有 15 个匹配节点
  • By.cssSelector(".hot") 有 11 个匹配节点
  • By.cssSelector(".ban.hot") 有 5 个匹配节点
  • By.cssSelector(".ban") has 15 matching nodes
  • By.cssSelector(".hot") has 11 matching nodes
  • By.cssSelector(".ban.hot") has 5 matching nodes

因此,您需要更多限制来缩小范围.选项 1 和 2 可用于 css 选择器,1 可能是最适合您需求的选项.

Therefore you need more restrictions to narrow it down. Option 1 and 2 below are available for css selector, 1 might be the one that suits your needs best.

选项 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)

Option 2: Using Selenium's FindElements, then index them. (CssSelector or XPath)

限制

  • 如果网站结构发生变化,则不够稳定
  • 不是原生选择器的方式

示例:

// note that By.CssSelector(".ban.hot") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case
IList<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"));

这篇关于需要通过 css 在 selenium 中找到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆