首页 > 解决方案 > 使用 selenium 和 python 从下拉列表中选择不起作用

问题描述

我正在尝试在 python 中开发一个脚本,将我记录在一个网站上,然后从下拉菜单中选择一个项目。我可以登录网站,但项目选择对我不起作用...我尝试了多个变体(find_by_id/xpath/visible_text 等),有无“.click()”或“select”。

网站:

<select style="font-size: 80%;position:relative; top:-1px;" name="testproject" onchange="this.form.submit();">
<option value="62802146" title="Project" selected="selected">Project</option>
      

我的代码:

def login(url,login, username, password, password, submit):
  driver.get(url)
  driver.find_element_by_id(login).send_keys(username)
  driver.find_element_by_id(password).send_keys(password)
  button = driver.find_element_by_xpath("/html/body/div/div[2]/form/div[3]/input").click()
  time.sleep(1)
  selected_project = Select(driver.find_element_by_xpath("/html/body/div[3]/div"))
  selected_project.select_by_value('62802146')
 

编辑: 错误

标签: pythonseleniumselenium-webdriverdrop-down-menuselenium-chromedriver

解决方案


这是一个基于角度的网站,需要显式等待。

wait = WebDriverWait(driver, 20)
select = Select(wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "select[onchange*='this.form.submit'][name='testproject']"))))
select.select_by_visible_text('Project')

进口:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

此外,我看到您使用的62802146值是 UI 中默认选择的选项,这就是您在浏览器自动化下拉菜单中看不到任何更改的原因,因此请尝试选择 2 oe 3 选项以查看重大更改。


推荐阅读