在Python的webdriver 2.4中,Select对象的正确导入语句是什么?
我正在用Python 2.7和Selenium WebDriver 2.4写测试。
文档(http://seleniumhq.org/docs/03_webdriver.html)展示了如何操作选择表单元素,示例代码如下:
Select select = new Select(driver.findElement(By.xpath("//select")));
select.deselectAll();
select.selectByVisibleText("Edam");
我想在Python中像这样操作选择表单元素。但是我不知道该导入什么才能成功创建Select对象。
我应该怎么写导入语句呢?
谢谢。
2 个回答
0
自从我发了这个问题后,我花了不少时间在找Python中和Java的Select()对象相对应的东西,但一直没找到。
我根据这个链接想出了一个解决办法:https://gist.github.com/1205069
也许下面的代码能帮到某些人,省点时间。
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
def select_by_text(web_element, select_text):
"""given a web element representing a select object, click the option
matching select_text
"""
option_is_found = False
options = web_element.find_elements_by_tag_name('option')
for option in options:
if option.text.strip() == select_text:
option.click()
option_is_found = True
break
if option_is_found == False:
raise NoSuchElementException('could not find the requested element')
# ...omitted setting up the driver and getting the page
web_element = webdriver.find_element_by_name('country_select')
select_by_text(web_element, 'Canada')
这段代码应该能根据给定的文本点击选择框,如果给定的元素不是选择框,或者文本不存在,就会抛出一个NoSuchElementException异常。
1
不过我搞不清楚要导入什么才能成功创建Select对象。
你可以这样导入:
from selenium.webdriver.support.ui import Select
另外,你可以查看这个链接了解更多信息:http://selenium.googlecode.com/svn/trunk/docs/api/py/webdriver_support/selenium.webdriver.support.select.html#module-selenium.webdriver.support.select