selenium+requests实现自动连接校园网并验证!

 

我为什么要加多个requests

在这次改进方案中,selenium主要承担的还是识别网页的title,进行一次判断。在上一篇文章中我也有提出,我的代码中的登陆后识别的部分代码是有缺陷的。今天突然想了想,可以采用更简单的方式去进行验证,那就是访问百度首页 ,对于访问这种简单网站,用selenium重新开一个窗口工程量稍微有点大,于是采用了requests来写这段内容,一下子就可以将selenium要很长处理的内容用短短两行完全表达了出来。

 
r = requests.get('http://www.baidu.com')
        if r.status_code == 200:

status_code是网页解析上可以看到的,关于具体的解析可以翻看我。其中status_code=200是常用的,这表示的是网页可以正常访问。

 

检测主要部分代码

def Is_OK():
    global IsCode
    #判断跳转界面
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    page_information = driver.find_element_by_css_selector('head > title').get_attribute('textContent')
    if page_information == '认证成功页':
        #判断联网
        r = requests.get('http://www.baidu.com')
        #print(r.status_code)
        if r.status_code == 200:
            IsCode = 0
            print("login successfully")
        else:
            IsCode = 1
            quit()
            login(account, password)
    elif page_information == '信息页':
        print("出现信息页,正在返回准备重新登录")
        back()
        login(account, password)
        IsCode = 1
    elif page_information == '上网登录窗':
        login(account, password)
        IsCode = 1
    return IsCode

可以看出,我这里采用的是页面验证+访问认证的方式。 如果你的电脑显示出了认证成功页,我才需要去检测是否联网;如果你的电脑还是显示的是信息页或者是上网登录窗,那么我暂时不需要检测联网,因为代码根本还没有帮你完成你所需要的东西。 关于这种思路,我也运用到了一开始的三个窗口识别中,检测如果你的认证呢成功页也是有网的话,我就主动退出了程序,这样节省大家的时间。

PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取

python免费学习资料以及群交流解答点击即可加入

 

 

检测的循环

检测我是用到了一个while循环,因为不知道具体要循环多少次才能检测成功,但我是设置了最多检测4次。在实际使用情况下,最多需要检测的次数只有2次,需要检测到第四次的时候,说明要不就是半夜断网的时刻或者就是你的账号密码输错了的情况,这种情况就需要你去进行判断了。 当然,关于账号密码输错的这种情况,除了手动删除代码生成的txt文件之外,还可以在代码中设置一些手段,在检测四次之后,自动返回之前,然后让你重新输入账号密码,覆盖本地文件,这种情况由于出现次数太少,我就没有写了,有兴趣的朋友可以研究研究,在这段代码中加入。

 

全部代码

#login_selenium.py
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
import time, os, requests
'''
NJUPT-CMCC/ChinaNet自动登录代码
author:海hong
本功能主要实现了对于登陆页面三个窗口的识别以及账号密码保存在本地的功能。
通过第一次登陆需要输入账号密码,以后登录就是一键便可完成,时间也很快,目前测试暂时没见bug。
'''
def txt_handle():
    global account, password
    try:
        f = open('校园网登录信息文件.txt', "r", encoding="utf-8")
        lines = f.readlines()
        print("已进入")
        account = lines[0]
        account = account.replace('\n', '')
        password = lines[1]
        f.close()
        #print(account, password)

    except Exception as e:
        account = input("请输入账号:")
        password = input("请输入密码:")
        txt = account + '\n' + password
        print(account, password)

        f = open('校园网登录信息文件.txt', "w+", encoding="utf-8")
        f.write(txt)
        print("文件信息已写入,请勿删除该文件!")
        f.close()
    return account, password

def login(account, password):
    #print(account, password)
    input_account = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '#edit_body > div.edit_row.ui-resizable-autohide > div.edit_loginBox.ui-resizable-autohide > form > input:nth-child(3)')))
    input_password = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '#edit_body > div.edit_row.ui-resizable-autohide > div.edit_loginBox.ui-resizable-autohide > form > input:nth-child(4)')))
    button = driver.find_element_by_css_selector('#edit_body > div.edit_row.ui-resizable-autohide > div.edit_loginBox.ui-resizable-autohide > form > input:nth-child(2)')

    input_account[0].send_keys(account)
    input_password[0].send_keys(password)
    #print("准备点击")
    button.click()

def back():
    button_back = driver.find_element_by_css_selector('#edit_body > div > div.edit_loginBox.ui-resizable-autohide > form > input')
    button_back.click()

def quit():
    button_quit = driver.find_element_by_css_selector('#edit_body > div > div.edit_loginBox.ui-resizable-autohide > form > input')
    button_quit.click()
    time.sleep(2)
    confirm = driver.switch_to.alert
    confirm.accept()
    print('你刚刚确认下线')
    time.sleep(5)
    confirm.accept()
    print('现在返回上网登录窗页面')

def Is_OK():
    global IsCode
    #判断跳转界面
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    page_information = driver.find_element_by_css_selector('head > title').get_attribute('textContent')
    if page_information == '认证成功页':
        #判断联网
        r = requests.get('http://www.baidu.com', timeout =30)
        #print(r.status_code)
        if r.status_code == 200:
            IsCode = 0
            print("login successfully")
        else:
            IsCode = 1
            quit()
            login(account, password)
    elif page_information == '信息页':
        print("出现信息页,正在返回准备重新登录")
        back()
        login(account, password)
        IsCode = 1
    elif page_information == '上网登录窗':
        login(account, password)
        IsCode = 1
    return IsCode

def Is_page():
    #判断跳转界面
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    page_information = driver.find_element_by_css_selector('head > title').get_attribute('textContent')

    if page_information == '上网登录窗':
        login(account, password)

    elif page_information == '信息页':
        back()
        login(account, password)

    elif page_information == '认证成功页':
        r = requests.get('http://www.baidu.com', timeout =30)

        if r.status_code == 200:
            IsCode = 0
            print("已登陆成功,无需重复登陆")
        else:
            quit()
            login(account, password)

    
    #检测页面是否跳转到认证成功页&能否正常上网
    count = 0
    while IsCode != 0:
        count = count + 1
        Is_OK()
        if IsCode == 1:
            print("第%s次验证无法通过"%str(count))
        else:
            print("第%s次验证通过"%str(count))

        if count == 4:
            print("验证次数过多,请注意是否断网或者账号密码出错!")
            break

url = 'http://p.njupt.edu.cn'
driver = webdriver.Chrome('chromedriver.exe')
wait = WebDriverWait(driver, 30)
driver.get(url)
account = 'XXXXXXXXXX'
password = 'XXXXXX'
IsCode = 1
txt_handle()
#print(account, password)

Is_page()

driver.quit()
print("5秒后窗口自动关闭")
time.sleep(4)
os.sys.exit()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值