一、按钮
input type=button
.click()方法,实现点击按钮功能
from selenium import webdriver from time import sleep driver = webdriver.Chrome() driver.get("http://sahitest.com/demo/clicks.htm") driver.find_element_by_xpath("/html/body/form/input[3]").click() sleep(2) text = driver.find_element_by_name("t2").get_attribute('value') if text == '[CLICK]': print('pass') driver.quit()注:该页面,点击click me按钮后,上面输入框会显示文本。
二、提交按钮
input type=submit
from selenium import webdriver from time import sleep driver = webdriver.Chrome() driver.get("http://www.baidu.com/") driver.find_element_by_id('kw').send_keys('storm啊') driver.find_element_by_id('su').click() sleep(3) driver.quit()
三、单选按钮
input tpye=radio
from selenium import webdriver from time import sleep driver = webdriver.Chrome() driver.get("http://sahitest.com/demo/clicks.htm") ele = driver.find_element_by_xpath('/html/body/form/input[7]')#注意这种xpath写法很不好 ele.click() sleep(2) if ele.is_selected(): print('pass') sleep(3) driver.quit()两个方法:
(1).click()
(2).is_selected() ,判断是否选中
四、复选框
input type=check box
from selenium import webdriver from time import sleep from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() driver.get("http://sahitest.com/demo/clicks.htm") ele = driver.find_element_by_xpath('/html/body/ul/li/a/label/input')#注意这种xpath写法很不好 ele.click() sleep(2) if ele.is_selected(): print('pass') sleep(3) ele.send_keys(Keys.SPACE) #自己可以手动实验下,按space键,可以选中或取消选中复选框 sleep(3) driver.quit()
如果我们想选中一个界面所有的复选框怎么办?或者依次点击一组单选按钮怎么办?先来观察一下,一组单选按钮或者复选框,name是相同的
我们通过name取一组button,放到一个list中,然后for循环操作
from selenium import webdriver from time import sleep driver = webdriver.Chrome() driver.get("http://sahitest.com/demo/keypress.htm") eles = driver.find_elements_by_name('a') for ele in eles: ele.click() sleep(2) driver.quit()
注意:
上面使用了一次发送SPACE 键来取消选中复选框
遇到过一次,元素被其它控件遮挡(元素能定位到),使用点击无法操作元素,报错
采用发送空格键,成功操作了元素。——很经典的一个坑。