使用python中的selenium从下拉菜单中选择多个选项

问题描述 投票:0回答:1

尝试搜索,但没有找到任何有效的解决方案。我有一个下拉菜单,如下所示,我想一次选择多个选项:

<select name="Area" multiple="" size="5" class="sel0"
onchange="opbygQvar('Area',dummyArray,false,true,false)">
<option value="">(blankstil)
</option><option value="1">1 A
</option><option value="2">2 B
</option><option value="3">3 C
</option><option value="4">4 D
</option><option value="5">5 E
</option><option value="6">6 F
</option></select>

试用代码:

driver.find_element_by_xpath("//select[@name='Area']/option[text()='1 A']").click()
driver.find_element_by_xpath("//select[@name='Area']/option[text()='2 B']").click()

只选择一个选项,然后将选择更改为其他选项,而不是选中多个选项。

任何帮助都非常感谢 - 提前感谢:)

python selenium selenium-webdriver
1个回答
2
投票

与手动操作一样,如果我们必须从多个选项下拉选择多个值,那么我们必须使用控制点击选择它。

同样,您必须使用Control click for Multiple Values自动化它。

参考您的案例示例:

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

element1 = driver.find_element_by_xpath("//select[@name='Area']/option[text()='1 A']")
element2 = driver.find_element_by_xpath("//select[@name='Area']/option[text()='2 B']")

ActionChains(driver).key_down(Keys.CONTROL).click(element1).key_up(Keys.CONTROL).perform()
ActionChains(driver).key_down(Keys.CONTROL).click(element2).key_up(Keys.CONTROL).perform()

您所要做的就是控制键绑定以选择多个值。请注意:您可以通过多种方式处理控制点击。参考文章:Click Here

© www.soinside.com 2019 - 2024. All rights reserved.