Python Selenium下拉菜单选择

时间:2018-10-01 23:53:35

标签: python selenium selenium-webdriver iframe webdriverwait

要在此page上单击“县”下拉菜单,我将此XPath与Selenium一起使用:

driver.find_elements_by_xpath('//div[@class="masterCustomDropDown"]/img')[3].click() 

由于有时它不会出错,也不会实际执行单击操作,因此我通常检查下拉菜单中的元素是否可见,以查看是否执行了单击功能。有更好的方法吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以尝试使用Select()

//Create a new select element
Select choose = new Select(driver.find_elements_by_xpath('//div[@class="masterCustomDropDown"]/img'))

//Select the element at the 3rd index in the Select element we have reference to
choose.selectByIndex(3)

答案 1 :(得分:0)

要点击下拉菜单,您需要:

  • 诱导 WebDriverWait 以使所需的框架可用并切换到
  • 诱使 WebDriverWait 使其可单击所需的元素,您可以使用以下解决方案:
  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    options = Options()
    options.add_argument("start-maximized")
    options.add_argument("disable-infobars")
    options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get("https://reports.blm.gov/report/LR2000/23/Pub-MC-Geo-Index")
    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"dispReport")))
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@title='County']//following::img[1]"))).click()
    
  • 浏览器快照:

Country