Search code examples
pythonseleniumselenium-webdriverxpathchrome-web-driver

Can we find xpath of a text in selenium python


Consider following table in webpage enter image description here

I want to know which are all companies are from country UK. So i have input as UK Can i find the xpath of this 'UK' by selenium python so that i can modify that xpath to get related output. Is this possible, please let me know.

Thanks in advance

Edit: I will give UK as input, I have to find corresponding companies in UK Answer : If table contains only texts, then xpath = "//td[text()='Country']/preceding-sibling::td" If table elements are having links to other pages
xpath - "//a[text()='Country']/parent::td/preceding-sibling::td" , then select ur element of ur choice to find answer

If ur not sure about using text , u can use //TAG[contains(text(),'TEXT')]

U can test ur xpaths in Google Chrome's "Developer Console" $any_variable("xpath")

Interested can go through https://www.w3.org/TR/2017/REC-xpath-31-20170321/#id-introduction to know how to query XPaths

Thanks


Solution

  • I suppose HTML like:

    <tr>
     <td>
         Island Trading
     </td>
     <td>
         Helen Bennet
     </td>
     <td>
         UK
     </td>
    </tr>
    ......  (more rows)
    
    
    # Make a for to get all TDs of each "important" TR, that is, 
    # a TR that includes a TD with 'UK' text
    for actualRow in self.driver.find_elements_by_xpath("//td[text()='UK']/parent::tr/td"):
        # Now select only the first TD
        thisRowsTD=actualRow[0]
        # Print information you need here (Text, id, name...)
        print(thisRowsTD.text)
    

    I hope this helps!