【问题标题】:Find element by xpath in selenium, with partial match在 selenium 中通过 xpath 查找元素,部分匹配
【发布时间】:2026-02-24 05:20:04
【问题描述】:

我有一个代码可以找到如下所示的元素:

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]。这可能吗?

【问题讨论】:

    标签: python selenium xpath


    【解决方案1】:

    如果该表格行内只有一个链接,您可以使用:

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

    如果该表行内有多个链接,您可能需要将 id 添加到 <a> 元素或特殊的 class 属性并将其用于选择:

    按 ID:

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

    按类别:

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

    或者如果分配了多个类:

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

    【讨论】:

    • 试过了,得到了[error] Element tr[@id='playerListPlayerId_9874']//a not found
    • 它是表格行内的唯一链接
    • 对不起,我错过了开头的//
    【解决方案2】:

    如果有多个链接具有相同的 xpath,您可能需要添加一个索引,因为结果是一个列表:

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

    【讨论】: