如何使用Python Selenium抓取隐藏的select元素

时间:2019-09-06 04:23:21

标签: python selenium select element hidden

当使用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")。 尽管看起来css_selector可用,但我找不到xpath(我得到了/html/body/div[1]/div[1]/div/div[1]/div/div/div[2]/div[2]/div[2]/div[2]/select)。我已经在Selenium中尝试了以下select方法,但到目前为止没有成功。

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 =选择(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

1 个答案:

答案 0 :(得分:0)

“隐藏的aria”并不是真正的隐藏元素,aria表示可访问的富Internet应用程序,其目的是使残疾人更容易访问应用程序。

此错误意味着元素的顶部(覆盖)上有东西(例如其他元素)。

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

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
相关问题