首页 > 解决方案 > Selenium webdriver:列出“输入”下拉列表的所有元素并选择不同的元素

问题描述

使用 python3 Selenium ChromeDriver,在此 URL 上:

https://www2.sgx.com/derivatives/products/chinaa50

  1. 如何获取合约月份列表。从 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>
    
  2. 如何从列表中选择不同的元素,从而导致相邻小部件重新加载?

下拉列表的 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 来引用它?

标签: python-3.xselenium-webdriverxpath

解决方案


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)   

推荐阅读