WebElement类的方法
1、清空(clear())
#!/usr/bin/python3
from selenium import webdriver
import time
chrome = webdriver.Chrome()
chrome.get('https://www.baidu.com')
chrome.find_element_by_id('kw').send_keys('python') #在百度输入框输入’python‘
time.sleep(3)
chrome.find_element_by_id('kw').clear() #清空输入框的内容
time.sleep(3)
2、获取元素的属性值(get_attribute())
#!/usr/bin/python3
from selenium import webdriver
import time
chrome = webdriver.Chrome()
chrome.get('https://www.baidu.com')
input_box = chrome.find_element_by_id('kw') #定位到输入框
print("百度输入框的class属性值是:%s"%input_box.get_attribute('class'))
time.sleep(3)
结果:
百度输入框的class属性值是:s_ipt
#!/usr/bin/python3
from selenium import webdriver
import time
chrome = webdriver.Chrome()
chrome.get('https://www.baidu.com')
input_box = chrome.find_element_by_id('kw') #定位到输入框
input_box.send_keys('selenium') #在输入框输入‘selenium’
print("百度输入框内输入的值是:%s"%input_box.get_attribute('value'))
time.sleep(3)
结果:
百度输入框内输入的值是:selenium
3、检查元素是否可见(is_displayed())
#!/usr/bin/python3
from selenium import webdriver
import time
chrome = webdriver.Chrome()
chrome.get('https://www.baidu.com')
input_box = chrome.find_element_by_id('kw')
print('百度输入框是否可见:%s'%input_box.is_displayed())
结果:
百度输入框是否可见:True
4、检查元素是否可编辑(is_enabled())
#!/usr/bin/python3
from selenium import webdriver
import time
chrome = webdriver.Chrome()
chrome.get('https://www.baidu.com')
input_box = chrome.find_element_by_id('kw')
print('百度输入框是否可见:%s'%input_box.is_enabled())
结果:
百度输入框是否可见:True
5、检查元素是否已被选中(is_selected())
#!/usr/bin/python3
from selenium import webdriver
import time
chrome = webdriver.Chrome()
chrome.get('https://www.baidu.com')
chrome.find_element_by_link_text('登录').click() #在百度首页点击登录
time.sleep(1) #等待1S(不等待的话可能页面未加载完导致后面元素定位不到)
chrome.find_element_by_id('TANGRAM__PSP_11__footerULoginBtn').click() #用户名登录
check_box = chrome.find_element_by_id('TANGRAM__PSP_11__memberPass') #定位到下次自动登录复选框
check_box.click() #取消选定状态
print('是否选中:%s'%check_box.is_selected())
time.sleep(3)
结果:
是否选中:False
6、提交(submit())
#!/usr/bin/python3
from selenium import webdriver
import time
chrome = webdriver.Chrome()
chrome.get('https://www.baidu.com')
chrome.find_element_by_id('kw').send_keys('软件测试')
chrome.find_element_by_id('su').submit()
time.sleep(3)