如何在Python selenium中通过部分文本进行选择

2024-10-01 00:29:02 发布

您现在位置:Python中文网/ 问答频道 /正文

如何通过下拉列表元素名称的一部分来选择该元素? 我想根据DB值选择一个选项,但该值没有下拉元素的完整名称,有没有办法让selenium使用我的数据库值作为部分文本来查找该选项

    modelo = googleSheet.modelo.upper().strip()
    select = Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div/div/div/div[1]/form/fieldset[6]/div/ul/fieldset[3]/div/ul/fieldset[3]/div/ul/fieldset/div/ul/li/label'))))
    select.select_by_visible_text(modelo)

我想选择的下拉选项是“Terrano II 2.7 xpto ol”,但我的数据库值只是Terrano II 2.7

谢谢你的帮助


Tags: div名称数据库元素列表db选项selenium
2条回答

如果先提取下拉文本内容,然后检查db查询是否为文本,会怎么样?大概是这样的:

Selenium Select - Selecting dropdown option by part of the text

driver.select_by_visible_text()已经做了strip()。你不需要它。 此外,根据此方法定义:

Select all options that display text matching the argument. That is, when given "Bar" this would select an option like:
<option value="foo">Bar</option>
:Args:
 - text - The visible text to match against

因此,您需要准确地预期可见的选项。 代码中的另一个问题是传递变量的方式

dropdown_option = "Some text you expect to see in the dropdown"
locator = driver.find_element_by_id("id")  # or any other locator
select = Select(locator)
        if locator is not None:
            for option in select.options:
                select.select_by_visible_text(dropdown_option) 

此实现使调试更容易。例如,在选择所需选项之前,可以打印下拉列表中的所有值

如果下拉列表打开需要花费大量时间,或者其他元素使下拉列表暂时不可见,请在选择之前添加单独的等待

from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By

 wait = WebDriverWait(driver, 10)
        wait.until(EC.visibility_of_element_located(
            (By.CSS_SELECTOR, "Unique css selector of the first option in dropdown")))

相关问题 更多 >