如何使用Python Selenium基于组合框从非选择下拉列表中选择选项

qgelzfjb  于 2023-02-12  发布在  Python
关注(0)|答案(2)|浏览(222)

尝试自动化一件事,我的工作,这是选择一个选项从下拉列表中的网站如下:
https://interparking-pl.my.site.com/abonament/s/?id=a0A58000000D7pZ
Selenium自动化在这种情况下不起作用。编写以下代码后:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chrome_driver_path = r"C:/Users/.../Projects/chromedriver.exe"

service = Service(executable_path=chrome_driver_path)
driver = webdriver.Chrome(service=service)
driver.get("https://interparking-pl.my.site.com/abonament/s/?id=a0A58000000D7pZ")
wait = WebDriverWait(driver, 10)
abo_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="combobox-button-53"]')))

执行后,我得到一条消息:

TimeoutException

如果通过标记名或任何其他选项查找元素,则会弹出以下消息:

Message: no such element: Unable to locate element

这个列表是建立在按钮标签上的,并且有一个 lightning 式的组合框结构,看起来好像没有可能点击下拉列表并自动选择所需的选项。
它需要对这些东西做一些不同的事情吗?
我期望使用Selenium在列表中的选项之间进行选择。

xyhw6mcr

xyhw6mcr1#

组合框是一个 * <button> * 元素。

另外,* id *(即combobox-button-53)是动态生成的,迟早会发生变化。它们可能会在下次重新访问应用程序或下次启动应用程序时发生变化。因此不能在定位器中使用。
溶液
要单击元素,需要为element_to_be_clickable()引入WebDriverWait,可以使用以下locator strategies之一:

  • 使用 * CSS选择器 *:
driver.get("https://interparking-pl.my.site.com/abonament/s/?id=a0A58000000D7pZ")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[name='subscriptionsTypeId']"))).click()
  • 使用 * XPATH *:
driver.get("https://interparking-pl.my.site.com/abonament/s/?id=a0A58000000D7pZ")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@name='subscriptionsTypeId']"))).click()
      • 注意**:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
  • 浏览器快照;

093gszye

093gszye2#

当我加载页面时,我得到如下的元素ID(XPATH)。//*[@id="combobox-button-51"]
也许数字51并不总是相同的?在这种情况下,尝试:

//*[starts-with(@id,'combobox-button-5')]

或者只是使用//*[@name="subscriptionsTypeId"],就像这里已经提到的另一个答案一样。

相关问题