在Selenium中按xpath查找元素,支持部分匹配
我有一段代码用来查找一个元素,代码大概是这样的:
driver.find_element_by_xpath("//tr[@id='playerListPlayerId_9874']/td[7]/a").click()
我希望能够只用下面的方式来查找:
driver.find_element_by_xpath("tr[@id='playerListPlayerId_9874']").click()
但是这样不行。我其实不想去处理 td[7] 这个部分。这样做有可能吗?
2 个回答
0
如果有多个链接的xpath是一样的,你可能需要加一个索引,因为结果是一个列表。
driver.find_element_by_xpath("//tr[@id='playerListPlayerId_9874']//a")[0].click()
4
如果在这个表格行里只有一个链接,你可以使用:
driver.find_element_by_xpath("//tr[@id='playerListPlayerId_9874']//a").click()
如果在这个表格行里有多个链接,你可能需要给这个<a>
元素加一个id,或者加一个特别的class
属性,然后用这个来选择:
通过id选择:
driver.find_element_by_xpath("//a[@id='THE_ID']").click()
通过class选择:
driver.find_element_by_xpath("//tr[@id='playerListPlayerId_9874']//a[@class='THE_CLASS']").click()
或者如果有多个class的话:
driver.find_element_by_xpath("//tr[@id='playerListPlayerId_9874']//a[contains(@class,'THE_CLASS'])]").click()