项目背景
需要通过web方式,批量修改百台设备密码。
之前爬虫采用python urllib和urllib2 库,利用这个库我们可以得到网页的内容,并对内容用正则表达式提取分析,得到我们想要的结果。比如Scrapy爬虫框架。
本文讲的采用的则是爬虫中的核武器——splinter,实现浏览器自动化操作。
什么是爬虫
爬虫能干嘛
splinter简单实现案例分享
Splinter介绍
Splinter是一个使用Python开发的开源Web应用测试工具。它可以帮你实现自动浏览站点和与其进行交互。splinter下载地址:https://pypi.python.org/pypi/splinter/
目前最新版本是0.7.3,测试平台是window7 64位。
环境配置
splinter默认浏览器是firefox。
本文使用的是chrome,需要下载chromedriver.exe,并放在chrome安装目录下。For Example:C:\Program Files (x86)\Google\Chrome\Application
并把C:\Program Files (x86)\Google\Chrome\Application添加到系统环境变量中。
代码实现
import time
from splinter import Browser
passwd="admin"
iplist=["192.168.1.1","192.168.1.2"]
if __name__ == '__main__':
for ip in iplist:
url='http://'+ip+'/cgi/login'
url2 = "http://"+ip+"/cgi/config"
try:
#configuration param 'chrome'
with Browser('chrome') as browser:
browser.visit(url)
# wait web element loading
time.sleep(1)
# fill in password
browser.fill('P2', "admin1")
# click the button of “登陆”
button = browser.find_by_value(u"登陆").first.click()
# wait web element loading
time.sleep(1)
browser.cookies.all()
browser.visit(url2)
# wait web element loading
time.sleep(1)
# fill in new password
browser.fill('P2', passwd)
# click the button of “生效”
button = browser.find_by_value(u"生效").first.click()
# wait web element loading
time.sleep(1)
except Exception as e:
print(e)
百度搜索案例
from splinter import Browser
import time
with Browser('chrome') as browser:
# Visit URL
url = "https://www.baidu.com"
browser.visit(url)
time.sleep(3)
browser.fill('wd', 'splinter - python acceptance testing for web applications')
time.sleep(3)
# Find and click the 'search' button
button = browser.find_by_id('su')
# Interact with elements
button.click()
time.sleep(3)
if browser.is_text_present('splinter.readthedocs.org'):
print("Yes, the official website was found!")
else:
print ("No, it wasn't found... We need to improve our SEO techniques")