python - selenium 通过 python 中的可见文本进行选择

标签 python selenium

您好,我正在尝试使用 selenium 使用实际文本而不是值选项从下拉列表中选择一个项目。我的脚本从列表中提取状态,并迭代状态,选择与列表匹配的下拉列表。 当我尝试以下代码时,它会抛出错误:

for agentinfo1, agentstate1 in zip(agentinfo, agentstate):
    select2 = driver.find_element_by_css_selector("#selst" %agentstate1)
    select2.click()

select2 = driver.find_element_by_css_selector("#selst" %agentstate1) TypeError: not all arguments converted during string formatting

我想知道错误是否被抛出,因为当我获取放入列表中的数据时,我附加了一个“\n”,但即使我取出该代码,它也不起作用。

最佳答案

您正在使用 CSS ID 而不是 CSS 类。 select2 是指向选择元素的指针,如果您的文本与变量中的文本完全相同

from selenium.webdriver.support.ui import Select

for agentinfo1, agentstate1 in zip(agentinfo, agentstate):
    select2 = Select(self.driver.find_element_by_id("<some id of the select element>")).select_by_visible_text(agentstate)

如果只是部分匹配,你可以尝试这个(不区分大小写的部分匹配):

from selenium.webdriver.support.ui import Select

for agentinfo1, agentstate1 in zip(agentinfo, agentstate):
    select2 = Select(self.driver.find_element_by_id("<some id of the select element>"))
    for each_option in select2.options:
        if agentstate.lower in each_option.text.lower:
            select2.select_by_index(int(each_option.get_attribute("value")))

关于python - selenium 通过 python 中的可见文本进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43812578/

相关文章:

python - OSError : out of pty devices 故障排除

python - 我们如何防止 FastAPI 中的 html 注入(inject)?

java - 具有相同类名的容器的 Xpath

java - 如何使用selenium多次运行同一类

javascript - 使用 capybara 捕获浏览器控制台日志

Python 多处理 : Killing a process gracefully

python - 彩色立方体塔

python - 在 seaborn facetgrid 的各个方面设置轴限制

javascript - 如何将 jQuery 与 seleniumexecute_script 方法一起使用?

selenium - 如何不连续重复依赖于该背景场景的 Cucumber 功能的背景场景