【问题标题】:how to select by a partial text in Python - selenium如何在 Python 中通过部分文本进行选择 - selenium
【发布时间】:2021-03-31 09:37:10
【问题描述】:

如何通过部分名称选择下拉元素? 我想根据数据库值选择一个选项,但是这个值没有下拉元素的完整名称,有没有办法让 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

感谢您的帮助

【问题讨论】:

  • 第一件事是 select 仅适用于 Select 标签。接下来是您可以使用 "//[contains(.,'{}')]".format("Terrano ll") 选择具有该值的选项。或以开头
  • 这是正确的。 “选择”仅适用于“选择”标签和“选项”标签作为下拉选项。

标签: python selenium drop-down-menu automation


【解决方案1】:

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")))

【讨论】:

    【解决方案2】:

    如果您首先提取下拉文本内容,然后检查您的数据库查询是否为文本,那会怎样?像这样:

    Selenium Select - Selecting dropdown option by part of the text

    【讨论】:

    • 我没有对你投反对票。我只是想让代码工作,因为它是 python 而解决方案不是,但感谢您的回答。我认为它正在某个地方:)
    • 是的,我知道它不是 python,但大多数 selenium 命令是相同的(或几乎相同)。因此,我认为您可以从那里开始..
    猜你喜欢
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多