web自动化之selenium

一、Selenium(http://www.selenium.org/)

  Web自动化测试工具。它支持各种浏览器,包括Chrome,Safari,Firefox等主流界面式浏览器,如果你在这些浏览器里面安装一个Selenium插件,那么便可以方便的实现Web界面的测试。换句话说叫 Selenium 支持这些浏览器驱动

  模拟浏览器的操作,例如表单操作,点击事件,键盘输入

二、内容

  安装、定位web元素、鼠标操作、键盘输入、窗口切换、cookie操作,调用js代码,窗口截屏,文件上传,警告框处理,多表单切换,等待.....

chrome浏览器驱动:https://sites.google.com/a/chromium.org/chromedriver/downloads

国内阿里云镜像:https://npm.taobao.org/mirrors/chromedriver

https://sites.google.com/a/chromium.org/chromedriver/

三、操作

from selenium import webdriver

wd = webdriver.Chrome()   # 创建一个对象

1. 基础操作

wd.get('http://baidu.com')  # 打开一个网页

title = wd.title  # 获取网页标题

print(title)  # 打印输出

wd.set_window_size(400,800)  # 设置窗口大小

wd.maximize_window()  #窗口最大化

2. 获取元素

wd.find_element_by_link_text('设置').click()  # 获取链接值,并执行点击操作

wd.find_element_by_link_text('搜索设置').click()  # 获取链接值,执行点击操作

sel = wd.find_element_by_xpath('//*[@id="nr"]')  # 通过xpath获取下拉列表

from selenium.webdriver.support.select import Select  # 下拉列表操作的模块

Select('sel').select_by_value('50')  # 更改下拉列表设置

3.多列表切换

实现 mail.126.com 的登录

from selenium import webdriver

import time

wd = webdriver.Chrome()

wd.get('https://mail.126.com/')

# wd.find_element_by_name('email').clear()

# wd.find_element_by_name('email').send_keys('zhanghao') # --- 报错,找不到元素

time.sleep(2)

fr = wd.find_element_by_id('x-URS-iframe')  # 获取表单

wd.switch_to_frame(fr)  # 切换到该表单中

time.sleep(3)

wd.find_element_by_name('email').clear()  # 清空该元素中的值

wd.find_element_by_name('email').send_keys('zhanghao')  # 对改元素发送值:zhanghao

 

4.窗口关闭

wd.close() 或者 wd.quit()

 

5.支持无窗口模式

from selenium import webdriver

from selenium.webdriver.chrome.options import Options  # webdriver 选项设置模块

import time

chrome_options = Options()  # 选项初始化

chrome_options.add_argument('--headless')  # 无窗口模式设置

wd = webdriver.Chrome(chrome_options=chrome_options)

wd.get('http://baidu.com')

title = wd.title

print(title)

time.sleep(2)

wd.close()

 

猜你喜欢

转载自www.cnblogs.com/petrolero/p/8934323.html