Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in DevOps and Agile by (19.7k points)

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

Here is the url:

<html class="">


<body class="homepage w1024 list">

    <script type="text/javascript">

    <article id="pagecontainer">

            <section class="body">

        <table id="container" cellspacing="0" cellpadding="0" 



    <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 class="s">

        <li class="s">

1 Answer

0 votes
by (62.9k points)

Only using class names is not sufficient in your case.

By.cssSelector(".ban") has 15 matching nodes

By.cssSelector(".hot") has 11 matching nodes

By.cssSelector("") has 5 matching nodes

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

Option 1: Using list items' index (CssSelector or XPath)


  • Not stable enough if the site's structure changes


 driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5"));


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


  • Not stable enough if the site's structure changes

  • Not the native selector's way


// note that By.CssSelector("") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case

IList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(""));

IWebElement banUsStates = hotBanners[3];

Option 3: Using text (XPath only)


  • Not for multi-lingual sites

  • Only for XPath, not for Selenium's CssSelector


driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']"));

Option 4: Index the grouped selector (XPath only)


  • Not stable enough if the site's structure changes

  • Only for XPath, not CssSelector


driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]"));

Option 5: Find the hidden list items link by href, then traverse back to h5 (XPath only)


  • Only for XPath, not CssSelector

  • Low performance

  • Tricky XPath


driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, '')]]/h5"));

Browse Categories