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

2024-10-05 13:14:29 发布

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

我正在使用Python中的Selenium工具包,并试图从下拉菜单中选择一个选项

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

例如:我正在寻找“W33”选项,网站上会显示“W33(只剩下4个)”。我想选择“W33(只剩下4个)”,但不知道如何实现这一点


Tags: text文本内容by工具包网站选项driver
2条回答

您可以在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.)

然后选择它:

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

资料来源:^{} at selenium-python documentation

由于可见文本的静态部分(即W33)后面总是跟着一个变量文本,例如(only 4 left)(only 3 left)等,因此^{}可能无效。你可能不得不考虑其中之一:


另类

作为替代方案,您也可以使用基于Locator Strategy,如下所示:

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,如下所示:

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

参考文献

您可以在以下内容中找到相关讨论:

相关问题 更多 >

    热门问题