from selenium import webdriver
dr = webdrover.Chrome()
dr.get('https://www.so.com/')
最大化浏览器:
dr.maximize_window()
设置浏览器大小:
dr.set_window_size(1000,1000)
dr.find_element_by_id('input').sned_keys('selenium自动化')
dr.find_element_by_id('search-button').click()
获取当前页面的URL:
print(dr.current_url)
后退:
dr.back()
前进:
dr.forward()
刷新:
dr.fresh()
元素操作
向输入框中输入元素:
inputBox = dr.find_element_by_id('input')
inputBox.send_keys('selenium自动化')
清除输入框中的元素:
inputBox.clear()
inputBox.send_keys('selenium自动化')
dr.find_element(By.ID,'search-button').click()
setting = dr.find_element(By.CSS_SELECTOR,'.show-list.setting-group > a')
检查元素是否可见:
print(setting.is_displayed())
获取指定元素的文本:
print(setting.text)
获取属性值
print(dr.find_element_by_id('input').get_attribute('class'))
隐性等待:
from time import ctime
设置隐性等待时长:
dr.implicitly_wait(20)
print(ctime())
dr.find_element(By.ID,'input')
print(ctime())
print()
print(ctime())
try:
dr.find_element(By.ID,'search-button666')
except:
print(ctime())
print(ctime())
显性等待:
导包:
from selenium.webdriver.support.ui import WebDriverWait
print(ctime())
WebDriverWait(dr,5,0.1)until(lambda dr:dr.find_element(By.ID,'input'))
print(ctime())
print()
print(ctime())
try:
WebDriverWait(dr,5,0.1)until(lambda dr:dr.find_element(By.ID,'input999'))
except:
print(ctime())
print(ctime())
提交数据:
inputBox = dr.find_element(By.ID,'input')
inputBox.send_keys('selenium自动化')
inputBox.submit()
当没有提交按钮的时候,submit()相当于回车键。
鼠标悬停:
from selenium.webdriver import ActionChains
dr.get('https://www.163.com/')
login = dr.find_element_by_class_name('ntes-nav-login-title')
ActionChains(dr).move_to_element(login).perform()
表单切换
定位到表单位置:
dr.get('https://www.163.com/')
login = dr.find_element_by_css_selector('#loginDiv > iframe')
进入表单:
dr.switch_to.frame(login)
dr.find_element_by_name('email').send_keys('第一个窗口')
退回默认表单
dr.switch_to.default_content()
dr.find_element_by_link_text('帮助').click()
窗口切换
windows = dr.window_handles
切换到第二个窗口
dr.switch_to.window(windows[1])
dr.find_element_by_css_selector('[name=word]').send_keys('第二个窗口')
关闭窗口
关闭第二个窗口
dr.close()
关闭第一个窗口
dr.switch_to.window(windows[0])
dr.close()
关闭浏览器
dr.quit()