Akshit
Akshit

Reputation: 113

How to extract element within a HTML Tag using Xpath in python?

I have an HTML tag that looks like this

<tr class="js-row  DC is-odd" data-nationality="Indian" data-team-id="3">
        <td class="top-players__freeze js-pos top-players__pos DC">2</td>
        <td class="top-players__freeze top-players__player">
            <div class="top-players__image">
                <img class="js-headshot" src="//static.iplt20.com/players/210/Photo-Missing.png" 

I'm trying to extract the data-nationality value using XPath, however I'm not quite sure how to do this.

I have tried something like this, after selecting the tr element:

driver.find_elements_by_xpath("//tr[contains(@class,'js-row  DC is-odd')]/@data-nationality")

However this didn't work. Can someone help me out with this?

Upvotes: 0

Views: 138

Answers (2)

David Weckerly
David Weckerly

Reputation: 56

Try using the get_attribute() element method.

driver.find_element_by_xpath("//tr[contains(@class,'js-row  DC is-odd')]").get_attribute("data-nationality")

https://www.geeksforgeeks.org/get_attribute-element-method-selenium-python/

Upvotes: 3

undetected Selenium
undetected Selenium

Reputation: 193088

Seems you were close enough. Presuming the value DC within class and data-team-id="3" being two unique attribute values within the element, to print the value of the data-nationality attribute i.e. Indian you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "tr.js-row.DC.is-odd[data-team-id='3']"))).get_attribute("data-nationality"))
    
  • Using XPATH:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//tr[@class='js-row  DC is-odd' and @data-team-id='3']"))).get_attribute("data-nationality"))
    
  • Console Output:

    Indian
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Upvotes: 0

Related Questions