0

Trying to read comments from Likedin feed by:

        comments = browesr.find_elements_by_xpath("//*[@class='comments-comments-list__comment-item comments-comment-item ember-view']")
        print(comments[0].id)
        print(comments[1].id)
        print(comments[2].id)
        print(comments[0].get_attribute("id"))
        print(comments[1].get_attribute("id"))
        print(comments[2].get_attribute("id"))
        print(comments[0].find_element_by_xpath("//*[@data-control-name='comment_actor_description']").text)
        print(comments[1].find_element_by_xpath("//*[@data-control-name='comment_actor_description']").text)
        print(comments[2].find_element_by_xpath("//*[@data-control-name='comment_actor_description']").text)

Output:

0.854587949237863-1
0.854587949237863-2
0.854587949237863-3
ember817
ember851
ember885
Ralph M.
out of network
3rd+
Managing Director at Intervi
Ralph M.
out of network
3rd+
Managing Director at Intervi
Ralph M.
out of network
3rd+
Managing Director at Intervi

As you can see the IDs are diffrent but the elements inside each one is the same one (the first one), what could be the issue?

Omri
  • 673
  • 4
  • 9
  • 25

2 Answers2

1

Just replace XPath

"//*[@data-control-name='comment_actor_description']"

with

".//*[@data-control-name='comment_actor_description']"
JaSON
  • 4,843
  • 2
  • 8
  • 15
  • I really appreciate the help. Could you please explain to me the meaning of the "." in the begining? – Omri Nov 06 '20 at 14:09
  • 1
    @Omri the dot in the beginning of XPath expression stands for [*context node*](https://stackoverflow.com/questions/1022345/current-node-vs-context-node-in-xslt-xpath) - `comments[0]`, `comments[1]`, ... – JaSON Nov 06 '20 at 14:20
-1

You cannot find an element with XPath again if you already have a web element with you. The solution to this is to use another mechanism such as id, class, name, tagname etc.

This will work.

Abhishek Puri
  • 345
  • 3
  • 6
  • 1
    No. This is not true. Chaining like `driver.find_element_by_xpath().find_element_by_xpath()` works fine – JaSON Nov 06 '20 at 12:46
  • Theoretically, it's true. but when you do this practically, selenium messes up the elements and you don't even get to understand the issue. – Abhishek Puri Nov 10 '20 at 04:12