如何使用 Selenium-Python 从多选列表中选择多个选项? [英] How to select multiple options from multi select list using Selenium-Python?

查看:29
本文介绍了如何使用 Selenium-Python 从多选列表中选择多个选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从具有 10 个选项的多个选择中选择 P0_ENGLISHP1_ENGLISHP5_ENGLISH.我只想选择这 3 个选项.

I am trying to select P0_ENGLISH, P1_ENGLISH, P5_ENGLISH from multiple select which has 10 options. I want to select only these 3 options.

HTML 代码:

<select multiple="" class="gwt-ListBox" style="height: 80px; width: 205px;">
    <option title="Generic_Eng" value="Generic_Eng">Generic_Eng</option>
    <option title="Generic_Hindi" value="Generic_Hindi">Generic_Hindi</option>
    <option title="P0_English" value="P0_English">P0_English</option>
    <option title="P0_Hindi" value="P0_Hindi">P0_Hindi</option>
    <option title="P1_English" value="P1_English">P1_English</option>
    <option title="P1_Hindi" value="P1_Hindi">P1_Hindi</option>
    <option title="P4_English" value="P4_English">P4_English</option>
    <option title="P4_Hindi" value="P4_Hindi">P4_Hindi</option>
    <option title="P5_English" value="P5_English">P5_English</option>
    <option title="P5_Hindi" value="P5_Hindi">P5_Hindi</option>
</select>

硒-蟒蛇代码:

queues = Select(driver.find_element_by_css_selector(".rowStyle1:nth-child(6) .gwt-ListBox"))
queues.select_by_visible_text("P0_English")
time.sleep(3)
queues.select_by_visible_text("P1_English")
time.sleep(3)
queues.select_by_visible_text("P5_English"

我试过使用这个代码.使用此代码,我可以选择第一个选项,即P0_ENGLISH".但是,在选择第一个选项后,出现错误:

I've tried using this code. With this code, I am able to select the first option i.e. "P0_ENGLISH". However, after selecting the first option I get an error:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

推荐答案

要从 Multi Select 元素中选择多个 options,您可以使用 ActionChains 模拟 Control Click 如下:

To select multiple options from a Multi Select element you can use ActionChains to mock Control Click as follows:

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

myElemA = driver.find_element_by_css_selector(".rowStyle1:nth-child(6) .gwt-ListBox option[value='P0_English']")
myElemB = driver.find_element_by_css_selector(".rowStyle1:nth-child(6) .gwt-ListBox option[value='P1_English']")
myElemC = driver.find_element_by_css_selector(".rowStyle1:nth-child(6) .gwt-ListBox option[value='P5_English']")
ActionChains(driver).key_down(Keys.CONTROL).click(myElemA).key_up(Keys.CONTROL).perform()
ActionChains(driver).key_down(Keys.CONTROL).click(myElemB).key_up(Keys.CONTROL).perform()
ActionChains(driver).key_down(Keys.CONTROL).click(myElemC).key_up(Keys.CONTROL).perform()

这篇关于如何使用 Selenium-Python 从多选列表中选择多个选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆