初始化
from selenium import webdriver browser = webdriver.Chrome() browser = webdriver.Firefox() browser = webdriver.Edge() browser = webdriver.PhantomJS() browser = webdriver.Safari()
访问页面
from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.taobao.com') print(browser.page_source) browser.close()
查找节点
单个节点
find_element_by_id #等价于find_element(By.ID, id) find_element_by_name find_element_by_xpath find_element_by_link_text find_element_by_partial_link_text find_element_by_tag_name find_element_by_class_name find_element_by_css_selector
多个节点
find_elements() lis = browser.find_elements_by_css_selector('.service-bd li')
节点交互
输入文字
send_keys()
清空文字
clear()
点击按钮
click()
动作链
例子
from selenium.webdriver import ActionChains #导入ActionChains source = browser.find_element_by_css_selector('#draggable') #要拖曳的节点 target = browser.find_element_by_css_selector('#droppable') #目标节点 actions = ActionChains(browser) #声明ActionChains对象并将其赋值为actions变量 actions.drag_and_drop(source, target) #调用actions变量的drag_and_drop()方法 actions.perform() #执行动作
执行JavaScript
browser.execute_script('window.scrollTo(0, document.body.scrollHeight)') browser.execute_script('alert("To Bottom")')
获取节点信息
获取属性
get_attribute()
获取文本值
input = browser.find_element_by_class_name('zu-top-add-question') print(input.text)
获取id、相对位置、标签名和大小
input.id input.location input.tag_name input.size
切换Frame
switch_to.frame() browser.switch_to.frame('iframeResult')
延时等待
隐式等待
browser.implicitly_wait(10)
显式等待
from selenium.webdriver.support.ui import WebDriverWait #引入WebDriverWait这个对象 from selenium.webdriver.support import expected_conditions as EC #等待条件 wait = WebDriverWait(browser, 10) #指定最长等待时间 input = wait.until(EC.presence_of_element_located((By.ID, 'q'))) #调用它的until()方法,传入要等待条件
等待条件
title_is # 标题是某内容 title_contains # 标题包含某内容 presence_of_element_located # 节点加载出来,传入定位元组,如(By.ID, 'p') visibility_of_element_located # 节点可见,传入定位元组 visibility_of # 可见,传入节点对象 presence_of_all_elements_located # 所有节点加载出来 text_to_be_present_in_element # 某个节点文本包含某文字 text_to_be_present_in_element_value # 某个节点值包含某文字 frame_to_be_available_and_switch_to_it # 加载并切换 invisibility_of_element_located # 节点不可见 element_to_be_clickable # 节点可点击 staleness_of # 判断一个节点是否仍在DOM,可判断页面是否已经刷新 element_to_be_selected # 节点可选择,传节点对象 # 节点可选择,传入定位元组 element_located_to_be_selected element_selection_state_to_be # 传入节点对象以及状态,相等返回True,否则返回False element_located_selection_state_to_be # 传入定位元组以及状态,相等返回True,否则返回False alert_is_present # 是否出现警告
前进和后退
back() forward()
Cookies
获取
get_cookies()
添加
browser.add_cookie({'name': 'name', 'domain': 'www.zhihu.com', 'value': 'germey'})
删除
browser.delete_all_cookies()
选项卡管理
# 开启一个新的选项卡 browser.execute_script('window.open()') # 获取当前开启的所有选项卡 window_handles # 切换选项卡 browser.switch_to_window(browser.window_handles[1])
异常处理
NoSuchElementException
无界面
chrome_options=webdriver.ChromeOption() chrome_options.add_argument('--headless') browser=webdriver.Chrome(chrome_options=chrome_options)