Python 当所有输入的功能都相同时,如何为按钮获取唯一的XPATH

Python 当所有输入的功能都相同时,如何为按钮获取唯一的XPATH,python,selenium,xpath,web-scraping,selenium-chromedriver,Python,Selenium,Xpath,Web Scraping,Selenium Chromedriver,我正在尝试使用python中的selenium web驱动程序提取NBA球员的统计数据,以下是我的尝试: from selenium import webdriver from selenium.webdriver.support.ui import Select browser = webdriver.Chrome() browser.get('https://www.basketball-reference.com') xp_1 = "//select[@id='selector_0

我正在尝试使用python中的selenium web驱动程序提取NBA球员的统计数据,以下是我的尝试:

from selenium import webdriver
from selenium.webdriver.support.ui import Select


browser = webdriver.Chrome()

browser.get('https://www.basketball-reference.com')

xp_1 = "//select[@id='selector_0' and @name='team_val']"
team = Select(browser.find_element_by_xpath(xp_1))
team.select_by_visible_text('Golden State Warriors')

xp_2 = "//select[@id='selector_0' and @name='1']"
player = Select(browser.find_element_by_xpath(xp_2))
player.select_by_visible_text('Jordan Bell')
我的问题是,在这个页面中有4个“Go”按钮,它们都具有相同的输入功能。换句话说,以下xpath返回4个按钮:

//input[@type='submit'and @name="go_button" and @id="go_button" and @value="Go!"]
我尝试按如下方式添加祖先,但未成功,但它不会返回xpath:

//input[@type='submit' and @name="go_button" and @id="go_button" and @value="Go!"]/ancestor::/form[@id='player_roster']

我很欣赏你的洞察力

尝试在XPAth下面选择所需的Go按钮:

"//input[@value='Go!' and ancestor::form[@id='player_roster']]"

请注意,在XPath表达式中不应混合使用单引号和双引号,正确使用
祖先
轴是必要的

//descendant_node/ancestor::ancestor_node

您还可以切换到CSS选择器并使用子代组合,在子代组合中,您可以使用父元素通过
Go
按钮限制为适当的形式

#player_roster #go_button
就是

browser.find_element_by_css_selector("#player_roster #go_button")
#是一个id选择器


CSS选择器通常比XPath更快,但旧IE版本除外。更多。

@Andersson感谢并为我在使用祖先时的错误道歉;我只是在学习selenium@QHarr-谢谢你的建议。CSS选择器相对于xpath的优缺点是什么?CSS选择器在大多数情况下比xpath更快,而且通常更健壮。
browser.find_element_by_css_selector("#player_roster #go_button")