Reputation: 1013
I am trying to extract NBA players stats using selenium web driver in python and here is my attempt:
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')
The problem I have is there are 4 "Go" buttons in this page and all have the same input features. In other words, the following xpath returns 4 buttons:
//input[@type='submit'and @name="go_button" and @id="go_button" and @value="Go!"]
I unsuccessfully tried adding ancestor as below but it does not return an xpath:
//input[@type='submit' and @name="go_button" and @id="go_button" and @value="Go!"]/ancestor::/form[@id='player_roster']
I appreciate any insight!
Upvotes: 1
Views: 334
Reputation: 84465
You could also switch to CSS selectors and use a descendant combination where you use an parent element to restrict to the appropriate form with Go
button
#player_roster #go_button
That is
browser.find_element_by_css_selector("#player_roster #go_button")
The # is an id selector.
CSS selectors are generally faster than XPath, except in cases of older IE versions. More info.
Upvotes: 1
Reputation: 52665
Try below XPAth to select required Go button:
"//input[@value='Go!' and ancestor::form[@id='player_roster']]"
or
"//form[@id='player_roster']//input[@value='Go!']"
Note that you shouldn't mix single and double quotes in a XPath expression and correct usage of ancestor
axis is
//descendant_node/ancestor::ancestor_node
Upvotes: 2