在python中使用硒从下拉菜单中选择多个选项

时间:2018-08-29 22:41:04

标签: python selenium selenium-webdriver

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

<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()

仅选择一个选项,然后将选择更改为另一个选项,而不保持选中多个选项。

我们非常感谢您的帮助-预先感谢:)

1 个答案:

答案 0 :(得分:2)

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

类似地,您必须通过使用Control单击多个值来使其自动化。

有关您的案例的示例:

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