2

The URL is enter link description here

Is there any way in selenium XPath to get value the element just the element which following sibling of located element

//span[contains(text(),"by")]//following-sibling::a

in this code I want to take the next element because sometimes it is not an anchor tag but span

For getting values of Author I am using the way, searching for "by" word element then

x_authors=driver.find_elements(By.XPATH,'//span[contains(text(),"by")]//following-sibling::a')    
x_authors_a=driver.find_elements(By.XPATH,'//span[contains(text(),"by")]//following-sibling::span[1]')

enter image description here

enter image description here

6
  • I think you could make your question clearer if you could edit it and add code blocks showing examples of the relevant HTML, including the case where the element you want is an a, and the case where it's a span. Commented Nov 1, 2022 at 12:21
  • 1
    By the way, since // is shorthand for /descendant-or-self::node()/, that makes your full XPath //span[contains(text(),"by")]/descendant-or-self::node()/following-sibling::a which selects any a elements which follow sibling elements which are either span elements containing 'by', or descendants of a span containing 'by'. Commented Nov 1, 2022 at 12:26
  • As you say, //following-siblig::a should give any element span or a ? But even in inspect mode it gives //span[contains(text(),"by")]//following-sibling::a only 10 there should be 16 Commented Nov 1, 2022 at 12:33
  • isn't it possible to add "and or" as in contains(). Like, //span[contains(text(),"by")]//following-sibling::a or following-sibling::span Commented Nov 1, 2022 at 12:43
  • No; following-sibling::a can only return a elements and will never return a span element Commented Nov 1, 2022 at 22:02

1 Answer 1

6

The following XPath will give exactly what you need:

"//span[text()='by ']/following-sibling::*[1]"

There are several points to be improved in your initial XPath:

  1. //span[contains(text(),"by")] matches more than 16 relevant elements.
  2. /following-sibling::* selects All the following siblings, of any tag name. But this selects all the following siblings, not only adjacent following siblings. To make this precise [1] index added.
Sign up to request clarification or add additional context in comments.

1 Comment

with your help, by this way, I could get the price tag value which was unable to get for two days, get_attribute('textContent') by using class attribute "a-offscreen" . Thanks

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.