Selenium2+python自动化(学习笔记2)
from selenium import webdriver
driver = webdriver.Ie()
driver.get=("http://www.baidu.com")
driver.refresh() #页面刷新
driver.back()#返回上一页
driver.forward()#切换下一页
driver.set_window_size(540,960)#设置窗口大小
driver.maximize_window()
driver.get_screenshot_as_file("d:\\test\\1.jpg")#截屏
driver.quit()
driver.find_element_by_id/name/class_name/tag_name/link_text/partial_link_text/css_selector/xpath()# 元素定位
模拟键盘的操作需要先导入键盘模块:from selenium.webdriver.common.keys import Keys
driver.find_element_by_ie("").send_keys(Key.ENTER)
鼠标事件需要先导入模块:from selenium.webdriver.common.action_chains import ActionChains
mouse = driver.find_element_by_link_text("设置")
ActionChains(driver).move_to_element(mouse).perform()
右击鼠标:context_click()
双击鼠标:double_click()
登录:
# coding:utf-8
from selenium import webdriver
import time
def login(driver, user, password):
driver.get("https://github.com/login")
driver.implicitly_wait(10)
driver.find_element_by_id("login_field").send_keys(user)
driver.find_element_by_id("password").send_keys(password)
driver.find_element_by_name("commit").click()
def logout(driver):
time.sleep(3)
driver.find_element_by_css_selector(".HeaderNavlink.name.mt-1").click()
time.sleep(1)
driver.find_element_by_css_selector(".dropdown-item.dropdown-signout").click()
driver.quit()
if __name__ == "__main__":
driver = webdriver.Firefox()
# 调用登录
login(driver, "youruser", "yourpsw")
print("hello yoyo!")
# 调用退出
logout(driver)
识别弹窗
不是所有的弹出框都叫alert,在使用alert方法前,先要识别出到底是不是alert。先认清楚alert长什么样子,下次碰到了,就可以用对应方法解决。
alert\confirm\prompt弹出框操作主要方法有:
text:获取文本值
accept() :点击"确认"
dismiss() :点击"取消"或者叉掉对话框
send_keys() :输入文本值 --仅限于prompt,在alert和confirm上没有输入框
一、认识alert\confirm\prompt
1.如下图,从上到下依次为alert\confirm\prompt,先认清楚长什么样子,以后遇到了就知道如何操作了
JS处理滚动条
# coding:utf-8
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://www.baidu.com")
print driver.name
## 回到顶部
#def scroll_top():
# if driver.name == "chrome":
# js = "var q=document.body.scrollTop=0"
# else:
# js = "var q=document.documentElement.scrollTop=0"
# return driver.execute_script(js)
# 拉到底部
#def scroll_foot():
# if driver.name == "chrome":
# js = "var q=document.body.scrollTop=10000"
# else:
# js = "var q=document.documentElement.scrollTop=10000"
# return driver.execute_script(js)
#滚动到底部
js = "window.scrollTo(0,document.body.scrollHeight)"
driver.execute_script(js)
#滚动到顶部
js = "window.scrollTo(0,0)"
driver.execute_script(js)
# 聚焦元素
target = driver.find_element_by_xxxx()
driver.execute_script("arguments[0].scrollIntoView();", target)