Python浏览器自动化工具splinter
# 介绍
Splinter 是用 Python 开发的一个开源web自动化测试的工具集。 它可以帮你自动化浏览器的行为,比如浏览 URLs 并和页面进行交互。
# 特点
- 简单的 api
- 支持多种 webdriver (chrome webdriver, firefox webdriver, phantomjs webdriver, zopetestbrowser, remote webdriver)
- 支持 css 和 xpath 选择器
- 支持 iframe 和 alert
- 可执行 javascript 脚本
- 支持 ajax 和 异步 javascript
# 安装
$ [sudo] pip install splinter
1
# Splinter文档
官方地址:http://splinter.readthedocs.io/en/0.7.7/ Chrome Driver文档:http://splinter.readthedocs.io/en/0.7.7/drivers/chrome.html
# 获取浏览器实例
from splinter import Browser
#默认是firfox浏览器,如果使用chrome等其他浏览器,需要安装相应的驱动
browser = Browser()
#使用chrome浏览器
#browser = Browser("chrome")
1
2
3
4
5
6
2
3
4
5
6
# 访问站点
browser.visit('http://www.baidu.com')
1
# 填充表单
方法名 | 说明 |
---|---|
fill(name, value) | 通过控件name赋值 |
fill_form(field_values) | 通过控件name赋值,参数是字典类型,即key为控件的name,字典项为要赋的值。支持text, password, textarea, checkbox, radio and select.checkbox必须制定字段字典项为boolean 类型 |
例如:为页面上name是wd的元素赋值,这里的wd是百度首页上的搜索框name
browser.fill("wd","splinter")
1
# 点击按钮
通过如下方法可以匹配页面上的dom元素
例如:找到页面上id是su的按钮,这里的su是百度首页上的"百度一下"按钮
button = browser.find_by_id('su')
button.click()
1
2
2
其中:click()方法表示单击该按钮
# 完整代码
实例说明:打开百度,根据关键字splinter搜索,如下实例会自动打开浏览器访问百度,搜索splinter
#coding=utf-8
from splinter import Browser
browser = Browser("chrome")
browser.visit('https://www.baidu.com')
browser.fill("wd","splinter")
browser.find_by_id("su").click()
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
最后更新时间: 2022/7/23 10:17:11