子选择元素按值不可能

问题描述 投票:0回答:1

我尝试使用以下代码使用硒选择一个元素:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select

print(f"Checking Browser driver...")
options = Options()
# options.add_argument('--headless=new')  
options.add_argument("start-maximized")
options.add_argument('--log-level=3')  
options.add_experimental_option("prefs", {"profile.default_content_setting_values.notifications": 1})    
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled') 
srv=Service()
driver = webdriver.Chrome (service=srv, options=options)    
waitWD = WebDriverWait (driver, 10)         

startLlink = "https://www.firmenabc.at/bauen-wohnen-einrichten"
driver.get (startLlink)     
select = Select(driver.find_element(By.XPATH,'(//select[@class="py-4"])[1]'))
select.select_by_value('1')

但我一直会出现此错误:

(selenium) C:\DEVNEU\Fiverr2025\PROGRAMS\FirmenABC>python test.py
Checking Browser driver...
Traceback (most recent call last):
  File "C:\DEVNEU\Fiverr2025\PROGRAMS\FirmenABC\test.py", line 25, in <module>
    select.select_by_value('1')
    ~~~~~~~~~~~~~~~~~~~~~~^^^^^
  File "C:\DEVNEU\.venv\selenium\Lib\site-packages\selenium\webdriver\support\select.py", line 84, in select_by_value
    raise NoSuchElementException(f"Cannot locate option with value: {value}")
selenium.common.exceptions.NoSuchElementException: Message: Cannot locate option with value: 1; For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception

,您可以看到这应该是第一个具有值=“ 1”

的元素

enter image description here

我如何使用硒选择第一个Opiton?

python selenium-webdriver
1个回答
0
投票
问题是选择选项需要片刻才能充分加载。我们可以通过自定义等待等待此操作,以确保选项数量大于1.

工程代码

from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import Select from selenium.webdriver.support.wait import WebDriverWait driver = webdriver.Chrome() url = "https://www.firmenabc.at/bauen-wohnen-einrichten" driver.get(url) wait = WebDriverWait(driver, 10) # close cookie popup wait.until(EC.element_to_be_clickable((By.ID, "CybotCookiebotDialogBodyButtonDecline"))).click() select = Select(driver.find_element(By.XPATH, "//label[text()='Bundesland']//select")) wait.until(lambda _ : len(select.options) > 1) select.select_by_value("1") driver.quit()
    
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.