经过测试的HTML:
<select>
<option value="html">html</option>
<option value="css">css</option>
<option value="JavaScript">JavaScript</option>
<option value="php">php</option>
</select>
isMultiple()
中没有像selenium.webdriver.support.select.Select(webelement)
这样的方法,也没有select_all()
方法Select(lang).select_by_visible_text("html")
Select(lang).select_by_visible_text("css")
Select(lang).select_by_visible_text("JavaScript")
Select(lang).select_by_visible_text("php")
然后尝试获取所有选定的选项。
Select(lang).all_selected_options
我只能得到最后一个选项'php',这意味着当我选择一个选项时,另一个选项被自动取消选择。all_selected_options
的含义是什么,options
是很有用的。我不能取消选择任何选项,因为只有一个选项被选中,报告了一个错误:
NotImplementedError: You may only deselect options of a multi-select
发布于 2019-12-12 09:22:47
如果要在python中使用selenium选择多个选项,可以始终使用ActionChains
链接一系列操作,在本例中需要以下操作:
CTRL
键Click
关于期权CTRL
密钥这里是在python中使用ActionChains的一个很好的例子
列出要在python中选择的选项列表,循环列表并使用xpath
选择包含text
的选项,然后使用ActionChains
使用上面定义的一系列操作来选择该选项。
# Text of options needed to select
options = ['html','css','php']
# Add path to your chrome drive
browser = webdriver.Chrome(executable_path="EXECUTABLE_PATH_HERE")
# Add url of website
browser.get("WEBSITE_URL_HERE")
for option in options:
# Find option that contains text equal to option
to_select = browser.find_element_by_xpath("//select/option[text()='"+option+"']")
# Use ActionChains
ActionChains(browser).key_down(Keys.CONTROL).click(to_select).key_up(Keys.CONTROL).perform()
ActionChains()
获取驱动程序的引用,即browser
。key_down()
按下传递给它的CONTROL
键。click()
单击使用xpath
选择的已传递选项。key_up()
发布CONTROL
密钥我希望这会对你有很大帮助。
发布于 2019-12-12 09:17:56
此下拉列表不支持多个选择,该下拉列表将具有multiple
属性
<select multiple="">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
没有is_multiple()
函数,但是有一个变量is_multiple
。它是在Select
__init__
中通过检查multiple
属性创建的
def __init__(self, webelement):
self._el = webelement
multi = self._el.get_attribute("multiple")
self.is_multiple = multi and multi != "false"
您可以使用Select
实例访问它。
Select(element).is_multiple
要获取所有下拉选项,不管它们是否被选中,请使用option
属性,这将以WebElement
列表的形式返回所有选项
options = Select(element).options
for option in options:
print option.text # html, css, ...
发布于 2019-12-12 10:28:55
根据您共享的HTML:
<select>
<option value="html">html</option>
<option value="css">css</option>
<option value="JavaScript">JavaScript</option>
<option value="php">php</option>
</select>
multiple
.标记没有属性<select>
所以它可能不是多选择下拉菜单。
要从<option>
标记中提取文本,可以使用以下任一定位器策略
tag_name
:
Select(driver.find_element_by_tag_name('select')) select_technology =select_technology.options中的选项: print(option.text)xpath
:
Select(driver.find_element_by_xpath(//select)) select_technology =select_technology.options中的选项: print(option.text)https://stackoverflow.com/questions/59300480
复制相似问题