selenium用法
例子
browser = webdriver.Chrome()
try:
browser.get(url)
input = browser.find_element_by_id('kw')
input.send_keys('Python')
input.sebd_keys(Keys.ENTER)
wait = WebDriverWait(browser, 10)
wait.until(EC.presence_of_element_located((By.ID, 'content_left')))
print(browser.current_url)
print(browser.get_cookies)
print(browser.current_source)
finally:
browser.close()
声明浏览器
browser = webdriver.Chrome()
访问页面
browser = webdriver.Chrome()
browser.get(url)
print(browser.page_source)
browser.close()
查找元素
单个元素
browser = webdriver.Chrome()
browser.get(url)
input_first = browser.find_element_by_id('q')
input_second = browser.find_element_by_css_selector('#q')
input_third = browser.find_element_by_xpath('//*[@id="q"]')
print(input_first,input_second,input_third)
browser.close()
- 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
多个元素
在上面的element后加s
以列表的形式储存多元素
多元素交互操作
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
input = browser.find_element_by_id('q')
input.send_keys('keys1')
time.sleep(1)
input.clear()
input.send_keys('keys2')
button = browser.fin_element_byclass_name(btn-search)
button.click()
执行JavaScript
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
browser.execute_script('alert('hello!')')
获取元素信息
获取属性
target = browser.find_element_by_id('')
target.get_attribute('class')
target.text
target.id
target.location
target.tag_name
target.size
Frame切换(父子frame中的元素不能跨越获取)
browser.switch_to.frame('...') // 切换到子frame
browser.switch_to.parent_frame() // 切换到父frame
等待
隐式等待
browser.implicitly_wait(10)
显式等待
browser.WebDriverWait(browser, 10)
input = wait.until(EC.presence_of_element_located((ByID, 'q')))
等待判断条件
title_is
title_contains
presence_of_element_located 是否出现
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
element_to_be_selected
element_located_to_be_selected
element_selection_state_to_be
element_located_selection_state_to_be
alert_is_present
前进后退
browser.back()
browser.forward()
Cookies
browser.get_cookies()
browser.add_cookie({'k1': 'v1', 'k2': 'v2'})
browser.delete_cookies()
选项卡管理
// 打开新的选项卡
browser.execute_script('window.open()')
// 切换选项卡
browser.switch_to_window(browser.window_handles[1])
操作...
browser.switch_to_window(browser.window_handles[0])
操作...
异常处理
try:
操作...
except TimeoutException:
print('TimeOut')
finally:
browser.close()