Wilson Wilson - 1 month ago 16
Python Question

Find element by xpath in selenium, with partial match

I have a code to find an element that looks like this:

driver.find_element_by_xpath("//tr[@id='playerListPlayerId_9874']/td[7]/a").click()


Id like to be able to find it only using:

driver.find_element_by_xpath("tr[@id='playerListPlayerId_9874']").click()


But that does not work. I basically do not want to have to deal with the td[7]. Is this possible?

Answer

If there is just one link inside that table row you can use:

driver.find_element_by_xpath("//tr[@id='playerListPlayerId_9874']//a").click()

If there are multiple links inside that table row you might need to add an id to the <a> element or a special class attribute and use that for selection:

by id:

driver.find_element_by_xpath("//a[@id='THE_ID']").click()

by class:

driver.find_element_by_xpath("//tr[@id='playerListPlayerId_9874']//a[@class='THE_CLASS']").click()

or if multiple classes are assigned:

driver.find_element_by_xpath("//tr[@id='playerListPlayerId_9874']//a[contains(@class,'THE_CLASS'])]").click()
Comments