seleinum中的方法汇总:

  •  提供键盘支持
from selenium.webdriver.common.keys import Keys

input.send_keys( Keys.RETURN )

# Keys.RETURN,
 Keys.F1,
 Keys.ALT,
 Keys.ARROW_DOWN 下方向键
  • 填写表格
from selenium.webdriver.support.ui import Select
# 导入类
select = Select(driver.find_element_by_name('name'))
# 将select元素实例化成对象,并选择我们要选择的option
select.select_by_index(index)
select.select_by_visible_text("text")
select.select_by_value(value)

#取消所有的选项
select = Select(driver.find_element_by_id('id'))
select.deselect_all()

#获得所有选项
options = select.options
  • 拖放
element = driver.find_element_by_name("source")
target = driver.find_element_by_name("target")

from selenium.webdriver import ActionChains
action_chains = ActionChains(driver)
action_chains.drag_and_drop(element, target).perform()
  • 在不同窗口和框架之间移动
# switch_to_window() 里面填入窗口名字
driver.switch_to_window("windowName")
# 可以打开他的javascript或者连接代码获取窗口名字
<a href="somewhere.html" target="windowName">Click here to open a new window</a>
# 窗口句柄: 可以遍历或者拿到某一个窗口
for handle in driver.window_handlers:
    driver.switch_to_window(handle)


# 可以切换到frame中
driver.switch_to_frame('framename')
  • 弹出对话框:
alert = driver.switch_to_alert()
  • 访问浏览器历史记录
driver.get("http://www.example.com")
# 前进或后退
driver.forward()
driver.back()
  • 操作cookie
# 获取cookie
cookies = driver.get_cookies()
# 设置cookie
driver.add_cookie( {'name':'foo'} )
  • 等待页面加载完成
# webdriverwait 结合 ExpectedCondition 实现显示等待
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.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()
  • 常用actionchains
    • click(on_element=None)  : on_element : the element to be click, if not, click on current mouse position
    • click_and_hold( on_element=None ) : 点击并按住
    • context_click( on_click=None )
    • move_to_element(to_element)
    • move_by_offset(xoffsetyoffset)
    • move_to_element_with_offset(to_elementxoffsetyoffset)
    • perform() : perform all stored actions
    • send_keys() : send keys to current focused element
    • send_keys_to_element(ele,  keys)   
02-13 13:45