代码之家  ›  专栏  ›  技术社区  ›  A.E

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

  •  1
  • A.E  · 技术社区  · 6 年前

    我正在尝试使用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']
    

    我很欣赏你的洞察力!

    2 回复  |  直到 6 年前
        1
  •  2
  •   Andersson    6 年前

    尝试使用下面的xpath选择所需的“执行”按钮:

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

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

    请注意,在xpath表达式中不应混合使用单引号和双引号,也不应正确使用 ancestor 轴是

    //descendant_node/ancestor::ancestor_node
    
        2
  •  1
  •   QHarr    6 年前

    您还可以切换到css选择器,并使用子代组合,其中使用父元素来限制使用 Go 按钮

    #player_roster #go_button
    

    那就是

    browser.find_element_by_css_selector("#player_roster #go_button")
    

    是一个ID选择器。

    除了旧的IE版本,CSS选择器通常比XPath更快。更多 info .