Selenium用法简介

Selenium 1 是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。这个工具的主要功能包括:测试与浏览器的兼容性——测试你的应用程序看是否能够很好得工作在不同浏览器和操作系统之上。测试系统功能——创建回归测试检验软件功能和用户需求。支持自动录制动作和自动生成 .Net、Java、Perl等不同语言的测试脚本。

优势

据 Selenium 主页所说,与其他测试工具相比,使用 Selenium 的最大好处是:
Selenium 测试直接在浏览器中运行,就像真实用户所做的一样。Selenium 测试可以在 Windows、Linux 和 Macintosh上的 Internet Explorer、Chrome和 Firefox 中运行。其他测试工具都不能覆盖如此多的平台。使用 Selenium 和在浏览器中运行测试还有很多其他好处。

下面是主要的两大好处:

通过编写模仿用户操作的 Selenium 测试脚本,可以从终端用户的角度来测试应用程序。通过在不同浏览器中运行测试,更容易发现浏览器的不兼容性。Selenium 的核心,也称browser bot,是用 JavaScript 编写的。这使得测试脚本可以在受支持的浏览器中运行。browser bot 负责执行从测试脚本接收到的命令,测试脚本要么是用 HTML 的表布局编写的,要么是使用一种受支持的编程语言编写的。

在这里插入图片描述
文档: https://selenium-python-zh.readthedocs.io/en/latest/index.html

安装:

pip install selenium

国内推荐使用豆瓣镜像源:

pip install -i https://pypi.douban.com/simple/ selenium
使用Selenium登录微博,模拟鼠标下滑操作:
# -*- coding: utf-8 -*-
__author__ = "One Fine"

from selenium import webdriver
from time import sleep

loginname = 'yourname'
password = 'yourpass'

brower = webdriver.Chrome(executable_path='D:/selenium/chromedriver.exe')
brower.get("https://www.weibo.com/")
sleep(5)  # 等待页面加载完成,以防找不到相应元素
brower.find_element_by_xpath('//*[@id="loginname"]').send_keys(loginname)
sleep(2)
brower.find_element_by_xpath('//*[@id="pl_login_form"]//input[@type="password"]').send_keys(password)
sleep(1)
brower.find_element_by_xpath('//*[@id="pl_login_form"]/div/div[3]/div[6]/a').click()

sleep(5)
# 模拟鼠标下滑
for i in range(3):
    brower.execute_script("window.scrollTo(0, document.body.scrollHeight); "
                          "var lenOfPage=document.body.scrollHeiht; return lenOfPage;")
    sleep(3)


# 关闭浏览器
sleep(10)
brower.quit()
设置chromdriver不加载图片
from selenium import webdriver
from time import sleep
chrom_opt = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images": 2}
chrom_opt.add_experimental_option("prefs", prefs)

brower = webdriver.Chrome(executable_path='D:/selenium/chromedriver.exe', chrome_options=chrom_opt)
brower.get("https://www.weibo.com/")

sleep(10)
brower.quit()

执行正常,图片没有显示,但是出现警告:DeprecationWarning: use options instead of chrome_options brower = webdriver.Chrome(executable_path='D:/selenium/chromedriver.exe', chrome_options=chrom_opt)

此时只需要chrome_options改成options2

brower = webdriver.Chrome(executable_path='D:/selenium/chromedriver.exe', options=chrom_opt)

然后重新运行就不会出现警告。


参考:
Selenium-Python中文文档 https://selenium-python-zh.readthedocs.io/en/latest/index.html
python selenium 定制启动Chrome的选项注意事项(十九) http://www.cnblogs.com/mengyu/p/9706770.html


  1. 参考: Selenium官方网站 ↩︎

  2. 参考:python selenium 定制启动Chrome的选项注意事项(十九) ↩︎

posted @ 2019-03-05 19:30  onefine  阅读(915)  评论(0编辑  收藏  举报