Selenium中的下拉菜单 - Python 3

时间:2017-05-25 04:33:23

标签: python python-3.x selenium drop-down-menu selenium-chromedriver

我正在尝试使用selenium访问下拉菜单,其格式如下:

<span class="k-pager-sizes k-label">
<span title="" class="k-widget k-dropdown k-header" unselectable="on" role="listbox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-owns="" aria-disabled="false" aria-readonly="false" aria-busy="false" aria-activedescendant="8e90d557-7e8d-4c5c-b906-202fd78c6d0a"><span unselectable="on" class="k-dropdown-wrap k-state-default">
<span unselectable="on" class="k-input">20</span><span unselectable="on" class="k-select">
<span unselectable="on" class="k-icon k-i-arrow-s">select</span>
</span>
</span>
<select data-role="dropdownlist" style="display: none;">
 <option value="10">10</option><option value="15">15</option>
 <option value="20">20</option><option value="50">50</option>
 <option value="100">100</option>
</select>
 <span>items per page</span>

我尝试了以下但没有成功:

try:
    driver = webdriver.Chrome('/Users/opusandcaymus/Election/chromedriver')
    driver.get('http://mcad-tx.org/Property-Search-Result?searchtext=Maple%20Branch')
    #dropdown=driver.find_element_by_xpath('//*[@id="grid"]/div[3]/span[2]/span/select')
    #select = Select(dropdown)
    dropdown = driver.find_elements_by_tag_name("option")
    for row in dropdown:
        print(row.value)
    driver.close()
except:
    print("error")
    driver.close()
    raise

有谁知道如何通过值找到选项?我想在每次打开页面时选择100。

1 个答案:

答案 0 :(得分:1)

您的选择下拉列表是隐藏的,因此我建议首先使用javascriptexecuter使其可见,然后选择值

使用以下代码:

element=driver.find_element_by_xpath("//select[@data-role='dropdownlist']")
driver.execute_script("arguments[0].setAttribute('style', 'display: block;')",element)
select = Select(element)
select.select_by_value("100")

另一种方式是使用Explicitwait 首先单击向下箭头和下拉列表,然后单击值100

类似python下面的代码:

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.XPATH, ".//*[@id='grid']/div[3]/span[2]/span/span/span[2]/span")))
element.click

element = wait.until(EC.visibility_of_element_located((By.XPATH, ".//ul[@data-role='staticlist']/li[5]")))
element.click

注意:请根据python语法进行更正