Selenium シミュレートされたログイン (Smart Nangong)

Selenium のシミュレートされたログイン

一連の考え

Selenium を使用してログインをシミュレートする方がリクエストを送信するよりも簡単であるため、この記事では Selenium を使用してログインを自動的にシミュレートします。Wisdom Nangong (南京理工大学のイントラネット ログイン検証インターフェイス) は更新後に確認コード検証を追加したため、この記事ではディープ ラーニングされた PaddleOCR を使用します。認証コードの認識精度は80%程度ですが、後段で認証コードの画像処理も行い、精度を高めます。
検証コード認識のアイデアとしては、1. Tesseract 認識pytesseract 2. 深層学習ネットワーク認識の 2 つを提供します。著者は初期段階では最初のアイデアを認識に使用しましたが、認識効果が非常に悪いことがわかり、フライングパドルの OCR モデルに切り替えました。
検証コードを保存するには、次の 2 つの方法があります。 1. 検証コードのリンクを見つけ、リクエストを直接使用して画像をダウンロードします。 2. Selenium のスクリーンショットを使用し、検証コードの座標とサイズを特定して、確認コードは後ほど表示されます (コンピュータのデフォルトのズーム率に注意してください)。
学習専用!

コード

実装プロセスは比較的簡単なので、コードを直接アップロードし、Selenium の環境を自分で構築する必要があります。

from selenium import webdriver
import time
import cv2 as cv
import numpy as np
from selenium.webdriver.common.by import By
import pytesseract
from PIL import Image
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutException
from paddleocr import PaddleOCR 
import operator
class login:
    
    def __init__(self,account,passward) :
        self.account=account
        self.passward=passward
        self.url="https://u.njtech.edu.cn/cas/login?service=https%3A%2F%2Fu.njtech.edu.cn%2Foauth2%2Fauthorize%3Fclient_id%3DOe7wtp9CAMW0FVygUasZ%26response_type%3Dcode%26state%3Dnjtech%26s%3Df682b396da8eb53db80bb072f5745232"
        print("自动化登陆开始!")
        # self.header={"User-Agent":" Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42",
        #              "Accept":" text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        #              "Content-Type": "text/html;charset=UTF-8"}
    def connect(self):
        options=webdriver.ChromeOptions()
        options.add_experimental_option("detach",True)

        driver=webdriver.Chrome(options=options)
        driver.get(self.url)
        driver.maximize_window()#全屏显示
        # time.sleep(10)
        # driver.implicitly_wait(5)#隐式等待
        
        self.save(driver)
        username=driver.find_element(By.ID,"username")
        username.send_keys(self.account)#账号
        passward=driver.find_element(By.ID,'password')
        passward.send_keys(self.passward)#密码
        code=self.save(driver)
        # code=self.img_ocr()
        print(code)
        yzm=driver.find_element(By.ID,"imgcaptcha")
        yzm.send_keys(code)
        
        
        driver.find_element(By.ID,"channelshow").click()#点击,触发隐式下拉框
        lis=driver.find_element(By.XPATH,'//*[@id="fm1"]/div/div[1]/div[1]/div[5]/div/span[3]')
        lis.click()

        # for li in lis:
        #     if"中国电信"in lis.text:
        #         li.click()
        #         break
        # driver.find_element(By.ID,"channelshow").send_keys("中国电信")
        
        # js='document.querySelector("#channel").removeAttribute("readonly");'#修改只读属性
        # driver.execute_script(js)
        
        # driver.find_element(By.ID,"channel").clear()
        # driver.find_element(By.ID,"channel").send_keys("中国电信")
        button=driver.find_element(By.ID,"login")
        button.click()
        driver.switch_to.window(driver.window_handles[-1])#跳转到新页面
        try:#验证是否登陆成功
            str=driver.find_element(By.XPATH,'/html/body/div/div[1]/div[2]/div')
            if operator.contains(str.text,"网络登陆:登录成功"):
                driver.implicitly_wait(5)#隐式等待
                driver.close()
                return True
        except:
            return False
        # try:
        #     WebDriverWait(driver,10).until(ec.presence_of_element_located(By.PATH,'/html/body/div/div[1]/div[2]/div[contains(.,"网络登陆:登录成功")]'))
        #     time.sleep(10)
        #     driver.close()
        # except TimeoutException:
        #     return False
    
    #selenium截图保存验证码图片,或者使用request直接下载验证码图片
    def save(self,driver):
        print("开始保存图片")
        path='D:\\code\\python\\Reptile\\code\\'
        code=driver.find_element(By.ID,'pc-captcha')
        #截图
        driver.save_screenshot(path+'page.png')
        loc=code.location
        size=code.size
        print("验证码坐标:",loc)
        print("验证码大小:",size)
        img=Image.open(path+'page.png')
        ##裁剪验证码
        #电脑默认缩放比为1.25
        code_img=img.crop((int(loc['x']*1.25),int(loc['y']*1.25),int(1.25*(loc['x']+size['width'])),int(1.25*(loc['y']+size['height']))))
        #使用飞桨OCR进行验证码识别
        ocr = PaddleOCR(use_angle_cls=True, lang="ch") 
        code_img=code_img.save(path+'code_img.png')
        result=ocr.ocr("D:\\code\\python\\Reptile\\code\\code_img.png",det=False)
        text=str(result)[4:8]
        
        print("验证码:",text)
        
        
        time.sleep(10)
        return text
        
        
if __name__=='__main__':
    acc='xxxxxxxxx'#自己账号
    passward='xxxxxx'#自己密码
    login=login(acc,passward)
    
    login.connect()

結果グラフ

画像の説明を追加してください

画像の説明を追加してください

おすすめ

転載: blog.csdn.net/m0_53192838/article/details/131044307