0

How do I find the element with text "Jessica" based on "3000" displaying in the web page using xpath?

I'm getting ...not a valid xpath error.

<div>
  <span><b>Jessica</b></span>
  <br>
  <label>Total Wealth ($):</label>
  <p>3000</p>
</div>

I tried this

RichestPersonName = browser.find_element_by_xpath("//p[text()='3000'] .. /span").text

but it shows

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //p[text()='3000'] .. /span because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//p[text()='3000'] .. /span' is not a valid XPath expression.

3 Answers 3

0

i tried this and it works. Managed to get 'Jessica'

RichestPersonName = browser.find_element_by_xpath("//p[text()='3000']/preceding-sibling::span").text

0

You should use the preceding-sibling Xpath option:

//p[text=()='3000']/preceding-sibling::span
2
  • this got me '3000'. i'm trying to get 'Jessica' based on '3000'.
    – AskNAnswer
    Jul 22, 2021 at 1:41
  • Sorry, changed that to preceding-sibling. Please retry.
    – Mate Mrše
    Jul 22, 2021 at 7:58
0

By selecting the correct approach of creating locators can make any automation framework more efficient. Xpath is one of the available options to locate any element in complex html web pages. With the help of XPath, tester can find the exact element by navigating through different hierarchies of web page. Like by using, any of these functions : Contains, Sibling and Parent etc.

In special scenarios where element needs to be located by referring to another element, any professional testing company prefer dynamic techniques of selecting element on a webpage using HTML DOM structure rather than making it hard coded.

Three possible ways to locate desired element in your case are given below :

  1. **/..** : "//p[text()='3000']/../span"

  2. **Preceding-Sibling** : "//p[text()='3000']/preceding-sibling::span"

  3. **Parent** : "//p[text()='3000']/parent::div/span"

These approaches will find the required node span with text 'Jessica' by navigating through other elements.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.