YosiFZ
YosiFZ

Reputation: 7900

Python Selenium get data with xpath from td inside tr

I'm using Selenium in my Python project, I want to get data inside a Table with this code:

xpath = "//div[@id='tab_highscore']//table[contains(@class, 'highscore')]//tr"
users = driver.find_elements_by_xpath(xpath)

for u in users:
    xpath = "//td[@class='name']"
    userTd = u.find_elements_by_xpath(xpath)[0]
    user = userTd.get_attribute('innerText')

    xpath = "//td[@class='score']"
    scoreTd = u.find_elements_by_xpath(xpath)[0]
    score = scoreTd.get_attribute('innerText')

    usersArr.append({"name":user, "ally":ally, "score":score})

The problem that in user and score I'm always getting the first tr values, any idea what is the problem?

Upvotes: 1

Views: 625

Answers (1)

JaSON
JaSON

Reputation: 4869

You need to specify context node (a dot in the beginning of XPath expression) that points to specific u on each iteration:

for u in users:
    xpath = ".//td[@class='name']"
    userTd = u.find_element_by_xpath(xpath)
    ...

P.S. Use find_element_by_xpath(xpath) instead of find_elements_by_xpath(xpath)[0] and .text instead of .get_attribute('innerText')

Upvotes: 1

Related Questions