Selenium WebDrivers 学习记录 - Select&CheckBox& 常用方法介绍

记录浏览器操作过程中,我们通经常碰到下拉框选择(Select),单选框(CheckBox)操作。

下拉框选择(Select)

以社区搜索为例
Selenium WebDrivers 学习记录 - Select&CheckBox& 常用方法介绍

from selenium import webdriver
from selenium.webdriver.support.select import Select

# 驱动路径
chromedriver_path=r"D:\Python\chromedriver.exe"
#创建FChrome WebDriver的实例
driver = webdriver.Chrome(chromedriver_path)
#打开网页
driver.get("http://support.i-search.com.cn")
#获取Select
sel=Select(driver.find_element_by_id('select_type'))
#选择
# sel.select_by_index(1)
# sel.select_by_value("1")
sel.select_by_visible_text("按标题")

Select 其他方法

  • selectByVisibleText(String text) 选中所有项的文字为指定值的项,与 deselectByValue 相反,但单选多选模式均有效,当没有适合的项时,抛出 NoSuchElementException 异常
  • selectByValue(String value) 选中所有 Select 标签中,value 为指定值的所有项,单选多选均有效,当没有适合的项时,抛出 NoSuchElementException 异常
  • selectByIndex(int index) 选中指定 index 的项,单选多选均有效,当 index 超出范围时,抛出 NoSuchElementException 异常
  • isMultiple() 判断下拉框是否多选模式
  • getOptions() 获得下拉框的所有项,单选多选模式均有效,当下拉框没有任何项时,返回空列表,不会抛出异常
  • getFirstSelectedOption() 获得第一个被选中的项,单选多选模式均有效,当多选模式下,没有一个被选中时,会抛出 NoSuchElementException 异常
  • getAllSelectedOptions() 获得所有选中项,单选多选模式均有效,但没有一个被选中时,返回空列表,不会抛出异常
  • deselectByVisibleText(String Text) 取消项的文字为指定值的项,例如指定值为 Bar,项的 html 为 Bar,仅对多选模式有效,单选模式无效,但不会抛出异常
  • deselectByValue(String value) 取消 Select 标签中,value 为指定值的选择,仅对多选模式有效,否则抛出异常 UnsupportedOperationException(不支持的操作)
  • deselectByIndex(int index) 取消指定 index 的选择,index 从零开始,仅对多选模式有效,否则抛出异常 UnsupportedOperationException(不支持的操作)
  • deselectAll() 取消所有选择项,仅对下拉框的多选模式有效,若下拉不支持多选模式,则会抛出异常 UnsupportedOperationException(不支持的操作)

单选框(CheckBox)

以社区登陆为例
Selenium WebDrivers 学习记录 - Select&CheckBox& 常用方法介绍

from selenium import webdriver

# 驱动路径
chromedriver_path=r"D:\Python\chromedriver.exe"
#创建FChrome WebDriver的实例
driver = webdriver.Chrome(chromedriver_path)
#最大化窗口
driver.maximize_window()
#打开网址
driver.get("http://support.i-search.com.cn/login?goto=http%3A%2F%2Fsupport.i-search.com.cn%2F")
#获取checkbox
cbox=driver.find_element_by_id('rememberLogin')
#checkbox是否有效
cbox_enabled=cbox.is_enabled()
print(cbox_enabled)
#checkbox是否选中
cbox_status=cbox.is_selected()
print(cbox_status)
if not cbox_status:
    #选中
    cbox.click()

Selenium WebDrivers 常用方法

  • clear() 如果找到的元素是 input 或  textarea,则清除它的值。其他元素不受影响。
  • click() 点击一个元素,元素必须可见,并且宽高都必须大于 0。如果这个点击操作导致页面刷新的话,
    必须要抛弃这个元素的所有引用,并且对这个元素的进一步操作,都会引发 StaleElementReferenceException
  • getAttribute(String name) 通过属性名,获得属性值。例如,我想获得 value 的值,可以调用 getAttribute(“value”)
  • getTagName() 获得该元素的标签名,例如 input,p 等
  • isDisplayed() 判断该元素是否可见
  • isEnabled() 判断元素是否可用
  • isSelected()判断元素是否被选中,只用于单选或者多选按钮 (radio button,check box)
  • sendKeys() 模拟输入字符
  • submit() 如果当前元素是一个 form 或者是在 form 内的一个元素,则会提交表单。
    否则,引发 NoSuchElementException