python - 如何使用 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
.
解决方案
“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
推荐阅读
- r - 如何使用 geom_text 在箱形图(ggplot2)中每个框的顶部添加文本?
- pyspark - Pyspark RDD 消除值中的无?
- zsh - 排除包含 $ 用于 rsync 副本的文件和目录
- android-studio - 无法在 AndroidStudio 4.2.1 上投射 InlineByteBuddyMockMaker
- salesforce - 使用 azure 数据工厂将增量数据从 Salesforce 加载到 azure synpase
- javascript - 如何从我的网页运行本地服务器脚本?
- c++ - 数组/向量的 CppRestSdk Json 反序列化
- java - 试图弄清楚为什么 arraylist 打印第一个值 2 次
- python - 如何在 Selenium Python 中所有打开的窗口上做几乎相同的事情?
- python - 我想用 keras 为深度学习添加一对一的层