python-3.x - Selenium webdriver:列出“输入”下拉列表的所有元素并选择不同的元素
问题描述
使用 python3 Selenium ChromeDriver,在此 URL 上:
https://www2.sgx.com/derivatives/products/chinaa50
如何获取合约月份列表。从 Chrome F12 看来,这是相应的 HTML。
<sgx-input-select class="sgx-input" name="" label="" hint="" message="" placeholder=""> <span class="sgx-input-hint-icon" style="visibility: hidden;"></span> <span class="sgx-input-hint"></span> <label class="sgx-input-select-label"> <span class="sgx-input-label" style="display: none;"></span><span class="sgx-input-select-filter-wrapper"><input is="sgx-select-filter" type="text" class="sgx-input-control sgx-input-select-filter" name="" placeholder="" readonly=""> <span class="sgx-select-filter-icon" title=""></span> </span> </label> <div class="sgx-input-message" style="display: none;"></div> <sgx-select-model style="display: none;"></sgx-select-model> </sgx-input-select>
如何从列表中选择不同的元素,从而导致相邻小部件重新加载?
下拉列表的 XPath 似乎是:
//*[@id="page-container"]/template-base/div/div/section[1]/div/sgx-widgets-wrapper/widget-derivatives-prices-and-chart/div[1]/div/div[2]/sgx-input-select
有没有更好的 XPath 来引用它?
解决方案
Contract Month
下拉菜单更具可读性的 Xpath将是
//div[text()='Contract Month']//following-sibling::sgx-input-select//input
Contract Month
下拉菜单的 CSS 选择器options
.sgx-select-picker-list .sgx-select-picker-option label .sgx-select-picker-label
你给了点击联系月份下拉菜单,然后options
使用上面的标识符找到。然后你可以点击选项
伪代码:
# Adding implicit wait
driver.implicitly_wait(10)
# Page has ajax loading where the dropdown loads slowly
# Adding sleep now. This has to be handled by webdriver wait
time.sleep(10)
dropdown = driver.find_element_by_xpath("//div[text()='Contract Month']//following-sibling::sgx-input-select//input")
# On clicking the dropdown, the options loads
dropdown.click();
options = driver.find_elements_by_css_selector(".sgx-select-picker-list .sgx-select-picker-option label .sgx-select-picker-label")
optionSize = len(options);
for index in range(optionSize - 1):
dropdown.click();
# Find the options again as click on Month will reset the options
options = driver.find_elements_by_css_selector(".sgx-select-picker-list .sgx-select-picker-option label .sgx-select-picker-label")
options.index(index).click()
# Page has ajax loading where the dropdown loads slowly
# Adding sleep now. This has to be handled by webdriver wait
time.sleep(10)
推荐阅读
- javascript - 如何在隐藏元素上停止 setinterval
- pandas - 按最多三列对 pandas 数据框中的示例进行排序
- hex - \x00@ 是什么意思?
- java - 从活动启动 Fragment 活动会导致 NullPointerException
- javascript - 制作用于将 URL 字符串转换为 JSON 的递归算法
- gitlab - 如何解决 GitLab 项目导出后管道损坏的问题?
- angular - 不完全禁用每个文件的严格模板
- r - 如何在 R 中操作数据框的因子水平?
- azure-active-directory - 如何使用 office365 使用 Azure AD 对 .net 核心 Web API 进行身份验证
- shell - Shell脚本,if语句检查环境变量的值