2019-03-15 Selenium 案例

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# @Time    : 2019/3/15 21:29

from seleniumimport webdriver

driver = webdriver.Chrome()# 可切换浏览器:Ie、Firefox

driver.maximize_window()# 浏览器窗口最大换

driver.implicitly_wait(8)# 设置隐式时间等待

driver.get("https://www.baidu.com")# 访问地址

driver.quit()# 关闭浏览器

# 完整的脚本例子-----------------------------

import time

from seleniumimport webdriver

driver = webdriver.Chrome()

driver.maximize_window()

driver.implicitly_wait(5)

driver.get("https://www.baidu.com")

driver.find_element_by_xpath("//*[@id='kw']").send_keys("selenium")

# 搜索输入框输入Selenium.xpath定位、find_elements找的是一组元素,返回的是一个列表;

driver.find_element_by_xpath("//*[@id='su']").click()# 点击百度一下按钮

time.sleep(2)# 导入时间模块,等待2秒

# 断言1

# 这里通过元素XPath表达式来确定该元素显示在结果列表,从而判断Selenium官网这个链接显示在结果列表。# 这里采用了相对元素定位方法/../

# 通过selenium方法is_displayed() 来判断我们的目标元素是否在页面显示。driver.find_element_by_xpath("//div/h3/a[text()='官网']/../a/em[text()='Selenium']").is_displayed()

driver.quit()

# 上述例子可把断言1换成断言2

# 断言2

ele_string = driver.find_element_by_xpath("//div/h3/a[text()='官网']/../a").text

if (ele_string ==u"Selenium - Web Browser Automation"):

print "测试成功,结果和预期结果匹配!"

# 网页上获取自己想要的信息----------------

# 例如:获取到页面下的一些邮件信息

from seleniumimport webdriver

import re

driver = webdriver.Ie()

driver.maximize_window()

driver.implicitly_wait(5)

driver.get("http://home.baidu.com/contact.html")# 页面地址

doc = driver.page_source# 得到页面源代码

emails = re.findall(r'[\w]+@[\w\.-]+', doc)# 利用正则,找出 [email protected] 的字段,保存到emails列表

for emailin emails:

print (email)

# 利用其他定位元素---------------------

from seleniumimport webdriver

driver = webdriver.Chrome()

driver.maximize_window()

driver.implicitly_wait(6)

driver.get("https://www.baidu.com")

try:# try except语句块来进行测试断言,这个在实际自动化测试脚本开发中,经常要用到处理异常

    driver.find_element_by_id("kw")# 用ID方式定位百度输入框的元素位置,

# 还有其他一些定位方式

# tag name: driver.find_element_by_tag_name("form");

# link text: driver.find_element_by_link_text("新闻").凡是看到链接元素上面有文字描述的都可以采取find_element_by_link_text()方法来进行元素定位

# partial link text: driver.find_element_by_partial_link_text("主页").click()、

# class name : driver.find_element_by_class_name("s_ipt")  class name定位、

# name : driver.find_element_by_name("wd") name定位、

# css : driver.find_element_by_css_selector("#su") 、 找 ‘百度一下’ 这个按钮、css定位方式

    print ('test pass: ID found')

except Exception as e:

print ("Exception found", format(e))

driver.quit()

# 清空输入文本----------------------

driver.find_element_by_id("kw").clear()

# 刷新页面方法---------------------

driver.refresh()

# 浏览器中的前进、后退操作-------------------

# driver.back()

# driver.forward()

import time

from seleniumimport webdriver

driver = webdriver.Chrome()

driver.maximize_window()

driver.implicitly_wait(6)

driver.get("https://www.baidu.com")

time.sleep(2)

elem_news = driver.find_element_by_link_text("新闻")

elem_news.click()# 点击进入到百度新闻time.sleep(2)

driver.back()# 从百度新闻后退到百度首页time.sleep(2)

driver.forward()# 百度首页前进到百度新闻time.sleep(2)

driver.quit()

# 获取浏览器版本----------------------------------

print (driver.capabilities['version'])

# current_url 方法可以得到当前页面的URL----------

print (driver.current_url)

# title方法可以获取当前页面的标题显示的字段-------

print (driver.title)

# 浏览器中重新开一个tab,利用键盘快捷键(ctrl+t)-----------------

ele = driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL +'t')

# 例

import time

from seleniumimport webdriver

from selenium.webdriver.common.keysimport Keys

driver = webdriver.Firefox()

driver.maximize_window()

driver.implicitly_wait(6)

driver.get("http://www.baidu.com/")

time.sleep(1)

ele = driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL +'t'# 触发ctrl + t

time.sleep(1)

# 点击单选框-----------------------------

for iin driver.find_elements_by_xpath("//*/input[@type='radio']"):

i.click()

# 例

from seleniumimport webdriver

driver = webdriver.Chrome()

driver.maximize_window()

driver.get('http://news.baidu.com')

driver.implicitly_wait(8)

for iin driver.find_elements_by_xpath("//*/input[@type='radio']"):

i.click()

# 点击复选框-----------------------------

import time

from seleniumimport webdriver

driver = webdriver.Ie()

driver.maximize_window()

driver.get('https://www.baidu.com')

driver.implicitly_wait(8)

driver.find_element_by_xpath("//*[@id='u1']/a[7]").click()

time.sleep(1)

driver.find_element_by_xpath("//*[@id='TANGRAM__PSP_10__footerULoginBtn']").click()

time.sleep(1)

driver.find_element_by_xpath("//*[@id='TANGRAM__PSP_10__memberPass']").click()

# 设置屏幕分辨率-----------------------------------

driver.set_window_size(1024, 768)

driver.set_window_size(1280, 800)

# 例

import time

from seleniumimport webdriver

driver = webdriver.Chrome()

driver.maximize_window()# 全屏driver.get('https://www.baidu.com')

time.sleep(1)

print (driver.get_window_size())

driver.set_window_size(1280, 800)# 分辨率1280*800

time.sleep(1)

print (driver.get_window_size())

driver.set_window_size(1024, 768)# 分辨率1024*768

time.sleep(1)

print (driver.get_window_size())

# title断言--------------------------------------------------

import time

from seleniumimport webdriver

driver = webdriver.Chrome()

driver.maximize_window()

driver.get('https://www.baidu.com')

time.sleep(1)

# 方法一try:

assert u"百度一下" in driver.title

print ('Assertion test pass.')

except Exception as e:

print ('Assertion test fail.', format(e))

# 方法二if u"百度一下,你就知道" == driver.title:

print ('Assertion test pass.')

else:

print ('Assertion test fail.')

print driver.title

# 获取错误信息进行对比、匹配------------------------------

import time

from seleniumimport webdriver

from selenium.webdriver.common.keysimport Keys

driver = webdriver.Firefox()

driver.maximize_window()

driver.implicitly_wait(6)

driver.get("http://www.baidu.com/")

time.sleep(1)

driver.find_element_by_xpath("//*[@id='u1']/a[7]").click()

time.sleep(1)

driver.find_element_by_xpath("//*[@id='TANGRAM__PSP_8__submit']").click()

# 断言方法一try:

error_message = driver.find_element_by_xpath(

"//*[@id='TANGRAM__PSP_8__error' and text()='请您填写手机/邮箱/用户名']").is_displayed()

print ("Test pass. the error message is display.")

except Exception as e:

print ("Test fail.", format(e))

# 断言方法二,本文重点介绍方法error_mes = driver.find_element_by_xpath("//*[@id='TANGRAM__PSP_8__error']").text

try:

assert error_mes ==u'请您填写手机/邮箱/用户名'

print ('Test pass.')

except Exception as e:

print ("Test fail.", format(e))

# 断言验证某个按钮是否被选中

from seleniumimport webdriver

import time

driver = webdriver.Ie()

driver.maximize_window()

driver.implicitly_wait(5)

driver.get("http://news.baidu.com/")

time.sleep(2)

# 验证元素大小是否符合需求设计---------------

import time

from seleniumimport webdriver

driver = webdriver.Firefox()

driver.maximize_window()

driver.implicitly_wait(6)

driver.get("https://www.baidu.com/")

time.sleep(1)

search_btn = driver.find_element_by_id('su')

print (search_btn.size)

# 页面文本全选操作ctrl+a------------------------

import time

from seleniumimport webdriver

from selenium.webdriver.common.keysimport Keys

driver = webdriver.Chrome()

driver.maximize_window()

driver.get('https://www.baidu.com')

element = driver.find_element_by_tag_name('body')

element.send_keys(Keys.CONTROL +'a')

# 退格键删除信息操作-------------------------

import time

from seleniumimport webdriver

from selenium.webdriver.common.keysimport Keys

driver = webdriver.Chrome()

driver.maximize_window()

driver.get('https://www.baidu.com')

element = driver.find_element_by_id('kw')

element.send_keys("Selenium automation")

time.sleep(1)

element.send_keys(Keys.CONTROL +'a')

element.send_keys(Keys.BACKSPACE)

# 鼠标右键操作,如:右键点开按钮,选择选项-----------------------

import time

from seleniumimport webdriver

from selenium.webdriverimport ActionChains

from selenium.webdriver.common.keysimport Keys

driver = webdriver.Chrome()

driver.maximize_window()

driver.get('https://www.baidu.com')

time.sleep(2)

element = driver.find_element_by_xpath("//*[@id='lg']/img")

actionChains = ActionChains(driver)

actionChains.context_click(element).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ENTER).perform()

actionChains.context_click(element).send_keys('i').perform()

# 如何执行js脚本-----------------------------------

# 实例一 执行js脚本触发一个alert弹出框

import time

from seleniumimport webdriver

driver = webdriver.Chrome()

driver.maximize_window()

driver.implicitly_wait(6)

driver.get("https://www.baidu.com")

time.sleep(1)

driver.execute_script("window.alert('这是一个alert弹框。');")# 注意这里的分号是英文输入法的分号,不能用中文

# 实例二 执行js脚本来控制浏览器竖向滚动条

# 打开百度贴吧,然后拖动滚动条到左侧 “地区”

# coding=utf-8

import time

from seleniumimport webdriver

driver = webdriver.Chrome()

driver.maximize_window()

driver.implicitly_wait(6)

driver.get("https://tieba.baidu.com/index.html")

time.sleep(1)

target_elem = driver.find_element_by_link_text("地区")

driver.execute_script("return arguments[0].scrollIntoView();", target_elem)# 用目标元素参考去拖动

driver.execute_script("scroll(0,2400)")# 这个是第二种方法,比较粗劣,大概的拖动

# 获取页面包含href元素的超链接,爬虫中常用-----------------

import time

from seleniumimport webdriver

driver = webdriver.Chrome()

driver.maximize_window()

driver.implicitly_wait(6)

driver.get("https://www.baidu.com")

time.sleep(1)

for linkin driver.find_elements_by_xpath("//*[@href]"):

print (link.get_attribute('href'))

driver.quit()

# 截图保存操作,测试脚本中有异常报错时可用的该方法--------------------------

import time

from seleniumimport webdriver

driver = webdriver.Chrome()

driver.maximize_window()

driver.implicitly_wait(6)

driver.get("https://www.baidu.com")

time.sleep(1)

driver.get_screenshot_as_file("C:\\Users\\你的账户名\\Desktop\\baidu.png")

driver.quit()

你可能感兴趣的:(2019-03-15 Selenium 案例)