user469216
user469216

Reputation: 61

Selecting multiple options from drop down menu using selenium in python

Tried searching but did not find any working solutions for this. I have a drop down menu as follows where I'd like to select multiple options at once:

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

Trial Code:

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

only selects one option and then changes selection to a different one instead of keeping multiple options checked.

Any help is highly appreciated - thanks in advance :)

Upvotes: 0

Views: 3395

Answers (1)

Ishita Shah
Ishita Shah

Reputation: 4035

As on Manual operation, if we have to select Multiple values from Multi options Drop down then We have to Select it by using Control click.

Similarly, You have to Automate it by using Control click for Multiple Values.

Example with reference to your case:

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

All you have to do is, control Key binding to select multiple values. Please Note: You can handle control click by multiple ways. Ref Post: Click Here

Upvotes: 2

Related Questions