如何使用 Selenium 和 Python 通过部分文本 select 下拉菜单中的选项

How to select an option from a dropdown menu through partial text using Selenium and Python

我在 Python 中使用 Selenium 套件,并尝试 select 从下拉菜单中选择一个选项。

为此我使用 python driver.select_by_visible_text() 。 我现在的问题是,可见文本始终包含我正在查找的值,但后来又添加了一些内容。 select_by_visible_text() 只是找到了确切的选项,但我不能准确命名它。

例如:我正在寻找选项 "W33",然后网站显示 "W33 (only 4 left)"。我想 select "W33 (only 4 left)",但不知道如何实现?

您可以使用 Select 对象上的 options 属性获取所有选项的列表:

from selenium.webdriver.support.ui import Select

elem = driver.find_element_by_id('myselect')
elem_select = Select(elem)
opts = elem_select.options

然后,检查其中哪些匹配。在您的示例中,检查 text 属性:

opts_to_select = [o for o in opts if o.text.startswith('W33')]
my_option = opts_to_select[0] # select first match
                              # (Maybe you also want to raise an error if 
                              # there is more than one match.)

和select它:

if not my_elem.is_selected():
    my_elem.click()

来源:Select at selenium-python documentation

作为可见文本的静态部分,即W33总是跟在可变文本之后,例如(only 4 left)(only 3 left)等,所以select_by_visible_text()不一定有效。您可能需要考虑其中之一:


备选

作为替代方案,您还可以使用 based ,如下所示:

driver.find_element_by_xpath("//select//option[contains(., 'W33')]").click()

Note: You may need to expand the <select> element first before clicking on the option.

理想情况下,您需要为 element_to_be_clickable() 引入 ,如下所示:

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select//option[contains(., 'W33')]"))).click()

注意:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

参考

您可以在以下位置找到相关讨论: