如何通过名称的一部分来选择dropdown元素?我想选择一个基于DB值的选项,但是这个值没有dropdown元素的完整名称,有没有办法让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)
I我想选择的下拉选项是"Terrano II 2.7xpto ol",但我的数据库值只有Terrano II 2.7。
谢谢你的帮助
发布于 2021-04-01 17:35:01
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)
这种实现使调试变得更容易。例如,您可以打印下拉列表中的所有值,然后再选择所需的选项。
如果需要很长时间才能打开dropdown,或者其他元素使您的dropdown暂时不可见,请在选择之前添加单独的等待。
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")))
发布于 2021-03-31 09:44:06
如果首先提取下拉文本内容,然后检查数据库查询是否为文本,会怎么样呢?如下所示:
Selenium Select - Selecting dropdown option by part of the text
https://stackoverflow.com/questions/66885177
复制相似问题