PhantomJS和Requests获取Busy值脚本

Zss 发表于:

需要实时的刷新并且记录当前工作信道的Busy值(信道繁忙程度),使用的是PhantomJS来模拟登陆获取到cookie,PhantomJS的exe文件需要和脚本在同一个文件夹

如上一篇文章所示,获取的方式有很多种,这是一种,这里也可以使用模拟请求的方式来获取cookie,不过我是用的直接操作浏览器来获取

获取到cookie后可以使用requests来模拟请求发送到接口url,返回需要的信息过滤掉多余的信息,留下busy值

#coding:UTF-8      
import requests,os,time
from lxml import etree
from selenium import webdriver

def get_cookie_url(ap_url): #模拟登录ap,获取ap界面的cookie并返回
    cookie =[]
    web = webdriver.PhantomJS()
    ap_url = 'http://{}'.format(str(ap_url))
    web.get(ap_url)
    web.implicitly_wait(30)
    web.find_element_by_xpath('//*[@id="cbi-input-user"]').send_keys('admin')
    web.find_element_by_xpath('//*[@id="cbi-input-password"]').send_keys('admin')
    web.find_element_by_xpath('//*[@id="cbi-home-button-login"]').click()
    web_cookie = web.get_cookies()[1]['value']
    url = web.current_url
    cookie.append(web_cookie)
    cookie.append(url)
    return cookie

def get_busy(radio,test,cookie): #构造headers和url,获取Busy值
    headers = {    'Referer':'{}/admin/status/radio0/common_status/'.format(str(cookie[1])),
                   'Cookie':'sysauth={}; sysauth=; loginuser=admin'.format(str(cookie[0]))
}
    url = '{}/admin/status/radio{}/common_status_refresh?_=0.6583448735609796'.format(str(cookie[1]),str(radio))
    number = 0
    arv_list = []
    path = '%s\Busy'%(os.getcwd())
    if os.path.exists(path) == False:
        os.makedirs(path)
    path = path + '\Busy_{}.log'.format(time.strftime("%Y-%m-%d-%H-%M-%S",time.localtime()))
    for index in range(0,int(test)):
        number += 1
        rsp = requests.get(url=url,headers=headers)
        xml = etree.HTML(rsp.content)
        Busy = xml.xpath('//*[@id="cbid.channelusage.0.busy"]/text ()')[0]
        Channel = xml.xpath('//*[@id="sortable_table"]/tr[3]/td[1]/text()')[0]
        arv_list.append(int(Busy))
        if radio == '0':
            with open(path,'a+') as file:
                file.write('第{}次刷新, 信道为:{},   2.4g的Busy为:{}%\n'.format(str(number),str(Channel),str(Busy)))
                print('第{}次刷新, 信道为:{},   2.4g的Busy为:{}%\n'.format(str(number),str(Channel),str(Busy)))
                file.close()
        else:
            with open(path,'a+') as file:
                file.write('第{}次刷新, 信道为:{},   5g的Busy为:{}%\n'.format(str(number),str(Channel),str(Busy)))
                print('第{}次刷新, 信道为:{},   5g的Busy为:{}%\n'.format(str(number),str(Channel),str(Busy)))
                file.close()

    avr = sum(arv_list)/len(arv_list)#计算平均值
    #print(avr)
    with open(path,'a+') as file:
        file.write('测试统计{}次的平均值为:{}%'.format(str(test),str(avr)))
        print('测试统计{}次的平均值为:{}%'.format(str(test),str(avr)))

if __name__=='__main__':
    print('--------------------------------------------  >>>')
    print(' 格式:ip地址 刷新次数 radio(0代表2.4g  1代表5g)')
    print(' 说明:用于收集工作信道的Busy值及其平均值')
    ap_url,test,radio = raw_input(' 例如:192.168.99.88 20 0\n').split()
    cookie = get_cookie_url(ap_url)
    get_busy(radio,test,cookie)