1

I'm looking to get the text "Interesting" which is the first occurrence of the class b after h1.important. How would I do that in Selenium?

<div class="a">
    <div class="b">Not interesting</div>
</div>
<div class="title">
    <h1 class="important">Title</h1>
</div>
<div class="a">
    <div class="b">Interesting</div>
</div>

Is there a way to find "Interesting" using a fancy selector or xpath? This would also match the first element: driver.find_elements_by_css_selector(".b").text

0

3 Answers 3

2
driver.find_elements_by_css_selector(".b")

this will return a list in Python-Selenium bindings. so you cannot do .text on it.

Instead try to use driver.find_element like below :

driver.find_element_by_css_selector("div.title+div>.b").text

in case you want to use xpath, try this :

driver.find_element_by_xpath("//div[@class='title']/following-sibling::div/div").text

Note that, CSS_SELECTOR is preferred over xpath in Selenium automation.

Sign up to request clarification or add additional context in comments.

Comments

1

This XPath

//h1[@class='important']/../following-sibling::*//*[@class='b']

Should give you the next b class occurrence after the h1.important node as you asking

Comments

1

This xpath should work

(//h1[@class="important"]/following::*[@class='b'])[1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.