0

I'm trying to get the span text for fourth class from the following html base for a specific nth iteration of that class in the html base.

<ul class="first_class">
    <li class="second_class ">
        <span class="third_class">
            <span class="fourth_class">100</span> 
        " temp_x"</span>
    </li>
    <li class="second_class ">
        <span class="third_class">
            <span class="fourth_class" title="200">200</span>
        " temp_y"</span>
        </li>
    <li class="second_class ">
        <span class="third_class">
            <span class="fourth_class">300</span>
        " temp_z"</span>
    </li>
</ul>

I was wondering if there is a way to specifically grab the 2nd and 3rd iteration so the output is 200 and 300

I'm only able to retrieve 100 which is from the first iteration using this:

self.driver.find_element_by_xpath("//span[@class='fourth class']").text
user9996043
  • 229
  • 1
  • 2
  • 13

2 Answers2

1

This can be done with the nth css selector. Also available with xpath

See this similar question for an example XPath query to get nth instance of an element

Sri
  • 2,281
  • 2
  • 17
  • 24
  • I tried the method you mentioned, but I can't seem to get it to work. Here are the to statements I tried, `self.driver.find_element_by_xpath("//li[@class='fourth_class ']")[1].text` and even `self.driver.find_element_by_xpath("//li[@class='second_class ']")[1].text`. Both result in `'WebElement' object is not subscriptable` – user9996043 Apr 13 '20 at 16:11
  • What you want to modify is the xpath, not the result from find_element_by_xpath. Try self.driver.find_element_by_xpath("(//li[@class='fourth_class '])[2]").text – Sri Apr 13 '20 at 16:13
  • `Message: no such element: Unable to locate element: {"method":"xpath","selector":"(//li[@class='fourth_class '])[2]"}` Doesn't seem to be working – user9996043 Apr 13 '20 at 16:20
  • `self.driver.find_element_by_xpath("(//span[@class='fourth_class '])[2]").text` changing `li` to `span` seems to have done the trick. – user9996043 Apr 13 '20 at 16:23
  • Ah yes, it would need to be span as that is the element with the class "fourth_class" – Sri Apr 13 '20 at 16:24
0

You can do this by getting the count of your locator using findElements. once you get count, you can traverse through loop using your xpath in the way.

List<WebElement> list=driver.find_element_by_xpath("//span[@class='fourth class']");
for(int i=0;i<list.size();i++)
{
driver.find_element_by_xpath("(//span[@class='fourth_class'])[i]").text;
}