键盘事件
send_keys可以用来模拟键盘输入
from selenium import webdriver from selenium.webdriver.common.keys import Keys #导入keys类 driver=webdriver.Chrome() driver.get('http://www.baidu.com') driver.find_element_by_id('kw').send_keys('python') # 通过回车键代替click driver.find_element_by_id('su').send_keys(Keys.ENTER) driver.quit()
send_keys(Keys.BACK_SPACE) #删除键(BackSpace) send_keys(Keys.SPACE) #空格键(Space) send_keys(Keys.TAB) #制表键(Tab) send_keys(Keys.ESCAPE) #回退键(Esc) send_keys(Keys.ENTER) #回车键(Enter) send_keys(Keys.CONTROL,‘a’) #全选(Ctrl+A) send_keys(Keys.CONTROL,‘c’) #复制(Ctrl+C) send_keys(Keys.CONTROL,‘x’) #剪切(Ctrl+X) send_keys(Keys.CONTROL,‘v’) #粘贴(Ctrl+V) send_keys(Keys.F1)# 键盘 F1 send_keys(Keys.F12) #键盘 F12
鼠标操作
Action Chains提供了鼠标操作的常用方法
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains driver = webdriver.Chrome() driver.get('http://www.baidu.com') link_element = driver.find_element_by_link_text('更多产品') ActionChains(driver).move_to_element(link_element).perform()
perform() #执行ActionChains中存储的行为 context_click() #右击 double_click() #双击 drag_and_drop() #拖动 move_to_element #鼠标悬停
浏览器操作
from selenium import webdriver driver = webdriver.Chrome() f_url = 'http://www.baidu.com' driver.get(f_url) s_url = 'http:news.baidu.com' driver.get(s_url) driver.back() #退回到f_url driver.forward() #前进到s_url driver.refresh() #刷新页面 driver.set_window_size(400,500) #设置浏览器大小
元素等待
time.sleep()
让程序强制等待一定时间,等待后继续运行
implicitly_wait()
它并不针对页面上的某一元素进行等待,当脚本执行到某个元素定位时,如果可以定位元素,则继续执行,如果元素无法定位,则driver会不断的判断元素是否被定位到。若超出implicitly_wait()设置的超时时间,则抛出异常
from selenium import webdriver from selenium.common.exceptions import NoSuchElementException driver = webdriver.Chrome() driver.implicitly_wait(10) #全局设置,在整个程序的运行过程中都会有效 driver.get('http://www.baidu.com') try: driver.find_element_by_id('kw123').send_keys('123') except NoSuchElementException as e: print(e) finally: driver.quit()
WebDriverWait()
等待某个条件成立时则继续执行,否则超时就抛出异常
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get('http://www.baidu.com') ele = WebDriverWait(driver,5,0.5).until( EC.presence_of_element_located((By.ID,'kw')) ) ele.sen_keys('python') driver.quit()
webDriverWait类是由WebDriver提供的等待方法
WebDriverWait(driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None)
webDriverWait()一般由until()或until_not()方法配合使用