自从上次写了校园网的软件,就更想深入的去优化和修改。
优化内容:
1.如果浏览器有问题原来将直接报错,现在已经全部可控制
2.浏览器登录完毕后,点击叉号会卡顿关闭
3.浏览器调用速度慢,整体代码复用度低
4.将账号和密码放在最前面,方便修改
新增内容:
1.这次采用了新的类的写法,采用python Selenium 4.15.2去写。
2.这次支持修改校园网地址,支持自定义登录内容
原本是想直接调用文件夹下的chromedrive,后来想还是调用系统自有的为上策
这次就不做多的介绍,要看介绍请看上一期https://blog.nuoyis.net/1053.html
这次就直接看代码
main.py
import getpass
import os
import sys
import time
from nuofunction import lianwang
if __name__ == "__main__":
# 校园网定义
xiaoyuanurl = "http://172.17.1.2"
# 校园网账号
xiaoyuanusername = ""
# 校园网密码
xiaoyuanpassword = ""
# 引入类
nuo = lianwang()
# 校园网连接性检测
if not (nuo.geturl(xiaoyuanurl)):
print("网络异常或不是校园网,请检查")
exit(1)
# 密码验证(防止盗登)
# sslogin = input("请输入分配给的给予的安全密码:")
password = getpass.getpass("请输入分配给的给予的安全密码:")
if password != "nu23o09":
print("密码错误")
input("按任意键关闭")
exit(1)
# 验证成功后开始检测是否登陆过
if not (nuo.openurl(xiaoyuanurl)):
print("浏览器内核调用异常,请检查")
input("按任意键关闭")
exit(1)
print("正在静默登陆中,请稍后....")
if True in nuo.find("xpath", "/html/body/div/div[1]/div[5]/input"):
print("检测到登录,开始执行")
nuo.shell("xpath", "click", "/html/body/div/div[1]/div[5]/input")
else:
print("未检测到登录,继续执行")
# 用户名
nuo.shell("xpath", "click", "/html/body/div/div[1]/form/input[1]")
nuo.shell("xpath", "clear", "/html/body/div/div[1]/form/input[1]")
nuo.shell("xpath", "element", "/html/body/div/div[1]/form/input[1]", xiaoyuanusername)
# 密码
nuo.shell("xpath", "click", "/html/body/div/div[1]/form/input[2]")
nuo.shell("xpath", "clear", "/html/body/div/div[1]/form/input[2]")
nuo.shell("xpath", "element", "/html/body/div/div[1]/form/input[2]", xiaoyuanpassword)
nuo.shell("xpath", "click", "/html/body/div/div[1]/form/button")
# 关闭浏览器内核
nuo.closeurl()
print("登录完毕,正在调用系统浏览器用于您检测是否登录成功")
os.popen("start " + xiaoyuanurl)
input("按任意键关闭")
nuofunction.py
# 部分写法借鉴 https://zhuanlan.zhihu.com/p/191566983
import os
import requests
import time
import urllib3
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.edge.options import Options as EdgeOptions
class lianwang:
def geturl(self, url):
try:
http = urllib3.PoolManager()
http.request('GET', url)
return 1
except Exception as e:
return 0
def touoptions(self):
# 头部设置
self.options.add_argument("--incognito")
self.options.add_argument('--no-sandbox')
self.options.add_argument('--headless')
self.options.add_argument('--disable-gpu')
self.options.add_argument('--ignore-certificate-errors')
self.options.add_experimental_option("excludeSwitches", ["enable-automation"])
self.options.add_experimental_option("useAutomationExtension", False)
return True
def openurl(self, url):
"""
打开网页
:param url:
:return: 返回 webdriver
"""
# 谷歌浏览器判断
try:
print("正在使用谷歌浏览器")
self.options = ChromeOptions()
self.touoptions()
# service = Service("./chromedriver.exe")
# os.path.join(os.path.abspath("."), "chromedriver.exe"))
# CHROMEDRIVER_PATH = "./chromedriver.exe"
# service = Service(executable_path=CHROMEDRIVER_PATH)
# self.driver = webdriver.Chrome(options=options)
self.driver = webdriver.Chrome(options=self.options)
self.driver.get(url)
return True
except:
print("谷歌浏览器调用失败,正在调用其他浏览器")
# 火狐浏览器判断
try:
print("正在使用火狐浏览器")
self.options = FirefoxOptions()
self.touoptions()
# service = Service("./chromedriver.exe")
# os.path.join(os.path.abspath("."), "chromedriver.exe"))
# CHROMEDRIVER_PATH = "./chromedriver.exe"
# service = Service(executable_path=CHROMEDRIVER_PATH)
# self.driver = webdriver.Firefox(options=options)
self.driver = webdriver.Firefox(options=self.options)
self.driver.get(url)
return True
except:
print("火狐浏览器调用失败,正在调用其他浏览器")
#Edge浏览器判断
try:
print("正在使用Edge浏览器")
self.options = EdgeOptions()
self.touoptions()
# service = Service("./chromedriver.exe")
# os.path.join(os.path.abspath("."), "chromedriver.exe"))
# CHROMEDRIVER_PATH = "./chromedriver.exe"
# service = Service(executable_path=CHROMEDRIVER_PATH)
# self.driver = webdriver.Firefox(options=options)
self.driver = webdriver.Edge(options=self.options)
self.driver.get(url)
return True
except:
print("Edge浏览器调用失败")
return False
def find(self, type, text):
"""
查找网页元素
"""
try:
if type == 'id':
elem = self.driver.find_element(By.ID, text)
elif type == 'name':
elem = self.driver.find_element(By.NAME, text)
elif type == 'class':
elem = self.driver.find_element(By.CLASS_NAME, text)
elif type == 'xpath':
elem = self.driver.find_element(By.XPATH, text)
elif type == 'css':
elem = self.driver.find_element(By.CSS_SELECTOR, text)
else:
return False, 0
except Exception as e:
return False, 0
return True, elem
def shell(self, type1, type2, text1, text2=''):
"""
综合判断并执行区
"""
_isOK, _strLOG = self.find(type1, text1)
if not _isOK: # 元素没找到,返回失败结果
return False
elem = _strLOG
# 点击
if type2 == "click":
try:
elem.click()
except Exception:
return False
return True
# 清除框中内容
elif type2 == "clear":
try:
elem.clear()
except Exception:
return False
return True
# 输入
elif type2 == "element":
try:
elem.send_keys(text2)
except Exception:
return False
return True
def closeurl(self):
self.driver.quit()
由诺依阁提供Hexo转Typecho软件支持