user5653362 user5653362 - 1 month ago 17
Python Question

Unable to locate xpath

Here is my HTML code:

enter image description here

I want to go to the tr where the label is CompanyId and get the td text which is 512571(last line). How can I achive this?

Here is what I tried:

driver.find_element_by_xpath('//label[contains(text(), "CompanyId")]').text

Sai Sai
Answer

The following xpath should work:

//th[label[contains(text(),'CompanyId')]]/following-sibling::td

Relevant line of code:

driver.find_element_by_xpath("//th[label[contains(text(),'CompanyId')]]/following-sibling::td").text

Note: by default the xpath will select the first occurrence of a td - in this case CompanyId looks like a label that is immediately followed by the data you are looking for. You could always use an index of you always want the first td

//th[label[contains(text(),'CompanyId')]]/following-sibling::td[1]