【问题标题】:Choosing from a Dropdown in Selenium--Element is not visible (Python)从 Selenium 中的下拉列表中选择——元素不可见(Python)
【发布时间】:2021-11-29 02:35:21
【问题描述】:

我正在尝试在此网站上抓取有关足球运动员的数据:https://understat.com/team/Aston_Villa/2021

此特定页面是阿斯顿维拉的页面。问题是我只需要从“最后 5 场比赛”中抓取数据。这是我附加的链接网页一半左右的下拉菜单。为了将其从“全部”更改为“5 场比赛”,我需要点击下拉菜单,选择“5 场比赛”,然后点击过滤器按钮。

我尝试选择“5 场比赛”选项,但如果不先单击该元素,则该元素不可见,而且我不知道之后如何单击“过滤器”按钮。

我试过select = Select(driver.find_element(By.NAME, 'team-players-n-last-matches')) select.select_by_value('5')

我试过了

driver.find_element_by_xpath("//select[@name='team-players-n-last-matches']/option[text()='5 games']").click()

但是这些都不起作用,因为 A) 元素仍然不可见,并且 B) 这些选项之后不会单击过滤器按钮。

总之,我需要:

A) 点击页面中间的“全部”下拉菜单

B) 选择“5 场比赛”选项

C) 点击过滤器按钮应用过滤器

感谢任何可以提前提供帮助的人!

亚当

【问题讨论】:

    标签: python selenium web-scraping


    【解决方案1】:

    这很棘手,因为下拉菜单有自定义样式和绑定。

    这是一种你可以得到你想要的东西的方法

    driver.execute_script('document.evaluate("//div[text()=\'All games\']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue?.click()')
    
    driver.execute_script('document.querySelector(\'[rel="5"]\').click()')
    
    driver.execute_script('document.querySelector(".fa.fa-filter").click()')
    

    我使用“所有游戏”这个词来识别您使用 xpath 定位的下拉列表的可点击 div,然后使用 rel 属性选择具有 5 个游戏的列表项,然后使用 .fa.fa-filter 类点击在过滤器按钮上

    【讨论】:

      【解决方案2】:

      要绕过driver.find_element 的元素可见性要求,您可以使用driver.execute_script 并运行自定义Javascript:

      from selenium import webdriver
      d = webdriver.Chrome('/path/to/chromedriver')
      d.get('https://understat.com/team/Aston_Villa/2021')
      d.execute_script("""
         document.querySelector('div.block:nth-of-type(4) div.filter:nth-of-type(2) .custom-select-styled').click()
         document.querySelector('div.block:nth-of-type(4) div.filter:nth-of-type(2) li[rel="5"]').click()
         document.querySelector('button#team-players-filter').click()
      """)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-25
        • 2020-12-01
        相关资源
        最近更新 更多