【问题标题】:selecting from dropdown menu with selenium从下拉菜单中选择硒
【发布时间】:2020-02-08 23:38:55
【问题描述】:

我试图在 python 中选择一个带有 selenium 的下拉菜单。 我无法让它工作。我已经尝试通过 xpath 在不同的链接上“单击”并且它可以工作。但我不知道下拉菜单。

这是我尝试使用的代码:

path = r"C:\Program Files\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(path)

driver.get("http://elpris.dk")

driver.find_element_by_xpath("""//*[@id="btnSelectProfile"]""").click()

【问题讨论】:

    标签: python selenium menu dropdown


    【解决方案1】:

    网页使用 Angular JS 编写,动态加载数据。因此,请使用 WebDriverWait 以使页面正确加载。

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    path = r"C:\Program Files\chromedriver_win32\chromedriver.exe"
    
    driver = webdriver.Chrome(path)
    driver.get("http://elpris.dk")
    delay = 15
    wait = WebDriverWait(driver, delay)
    try:
        elem = wait.until(
               EC.element_to_be_clickable((By.ID, 'btnSelectProfile')))
        elem.click()
    except Exception as e:
        print(e)        
    

    另一种选择是添加一些睡眠以等待数据正确加载,如下所示:

    import time
    path = r"C:\Program Files\chromedriver_win32\chromedriver.exe"
    driver = webdriver.Chrome(path)
    
    driver.get("http://elpris.dk")
    time.sleep(3)
    driver.find_element_by_xpath("""//*[@id="btnSelectProfile"]""").click()
    

    然后点击就会生效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多