首页 > 解决方案 > 如何使用 Python Selenium 抓取隐藏的选择元素

问题描述

当使用 Python Selenium 抓取带有隐藏下拉选择元素的网页时,我收到消息“ElementNotInteractableException:无法将元素滚动到视图中”。

这是网页的部分:

<select class="period-selection select2-hidden-accessible" tabindex="-1" aria-hidden="true" style="">
<option value="quarterly">Quarterly</option>
<option value="annual" selected="selected">Annual</option>
<option value="ttm">TTM by Quarter</option></select>

特定select元素没有 id 或名称,并且看起来是hidden ("aria-hidden = True"). 我找不到 xpath(我得到了/html/body/div[1]/div[1]/div/div[1]/div/div/div[2]/div[2]/div[2]/div[2]/select),虽然看起来 css_selector 是可用的。我select在 Selenium 中尝试了如下方法,但到目前为止还没有成功。

PeriodType = Select(driver.find_element_by_css_selector('.period-selection'))
PeriodType.select_by_value('quarterly') #got "ElementNotInteractableException: Element <option> could not be scrolled into view"    
PeriodType.select_by_index(1) #got "ElementNotInteractableException: Element <option> could not be scrolled into view"
PeriodType.select_by_visible_text('Quarterly') #got "ElementNotInteractableException: Element <option> could not be scrolled into view"

我还看到了使用的建议

PeriodType = driver.find_element_by_css_selector('.period-selection')
driver.execute_script("arguments[0].scrollIntoView();", PeriodType)

但这到目前为止对我也没有用,或者我不确定如何实施。

我也尝试将 WebDriverWait 用作: PeriodType = driver.find_element_by_xpath("//select[@class='period-selection select2-hidden-accessible']") dropDownMenu = Select(PeriodType) WebDriverWait(driver, 10).until (EC.element_to_be_clickable((By.XPATH, "//select[@class='period-selection select2-hidden-accessible']//options[contains('Quarterly')]"))) dropDownMenu.select_by_visible_text('Quarterly ')

但是,我得到了“引发 TimeoutException(消息,屏幕,堆栈跟踪)

TimeoutException”消息与上面的代码。

我希望能够自动选择quarterly.

标签: pythonseleniumselectelementhidden

解决方案


“aria-hidden”并不真正意味着元素被隐藏,aria 代表Accessible Rich Internet Applications,其目的是使应用程序更容易被残障人士访问。

此错误意味着某些东西(例如其他元素)位于元素的顶部(覆盖)。

在使用之前尝试滚动到元素,例如:

dropdown = driver.find_element_by_css_selector('.period-selection')

actions = ActionChains(driver)
actions.move_to_element(dropdown).perform()

Select(dropdown).select_by_visible_text('Quarterly')

您需要导入 ActionChains

from selenium.webdriver.common.action_chains import ActionChains

推荐阅读