1

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

2 Answers2

3

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!

nugbe
  • 139
  • 1
  • 5
  • 1
    Thanks @nugbe It worked. As i have mentioned wrong code above it had some conflicts. But Thanks it helped me to figure out the problem i am facing. i forgot to mentioned that those are not text but actually links in the table. I used xpath as "//a[text()='Country']/parent::td/preceding-sibling::td". Then i found 1st element in the result – Raghavendra Phayde May 01 '20 at 02:28
0

Yes you can using text attribute, let's say the element containing country name is td.
Then you can find all elements with UK text through :

elements= driver.find_elements_by_xpath("//td[text()='UK']")
Rola
  • 1,598
  • 13
  • 12