搜尋
首頁後端開發Python教學Python怎麼實現取得網頁內容及自動填表單與登入功能

import time
import ddddocr

原始碼

# import threading  # 导入threading模块
# from Feishu_SendMsg import *

# Identification verification code
import time
import ddddocr


interval = 100 * 60

# def delayCall():  # 定义方法
#     SendMsg("选题 快快快!!!")

#     timer=threading.Timer(interval,delayCall)  # 每秒运行
#     timer.start()  # 执行方法
    
# if __name__ == '__main__':  #
#     t1=threading.Timer(interval,function=delayCall)  # 创建定时器
#     t1.start()  # 开始执行线程


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys


# SendMsg("自动填表单")
options = webdriver.ChromeOptions()
options.add_argument('--enable-automation')
options.add_argument('--no-sandbox')
options.add_argument('--disable-extensions')
options.add_argument('--start-maximized')
options.add_argument('--disable-infobars')

prefs = {"profile.default_content_setting_values.autocomplete_enabled": 2}
options.add_experimental_option("prefs", prefs)

# SendMsg("创建 Chrome 浏览器实例")
# 创建 Chrome 浏览器实例
browser = webdriver.Chrome(options=options)

# SendMsg("打开网页")
browser.get('www.tttttttt.com')

# SendMsg("找到账号和密码框元素并输入指定字符串")
username = browser.find_element("name","username")
password = browser.find_element("name","userpass")
usercode = browser.find_element("name","usercode")
img_verifycode = browser.find_element("id","img_verifycode")

# SendMsg("自动填充账号密码")
username.send_keys("11111")
password.send_keys("11111")

verifycodeBase64 = img_verifycode.screenshot_as_base64
ocr = ddddocr.DdddOcr()
res = ocr.classification(verifycodeBase64)
usercode.send_keys(res)
# SendMsg(f"识别并填写验证码: {res}")

# SendMsg("提交表单")
password.send_keys(Keys.RETURN)
# SendMsg("登陆: 提交表单")

知識點補充

#下面為大家介紹一下文中用到的ddddocr函式庫的相關使用吧

#識別驗證碼的python 函式庫很多,用起來也不簡單,ddddocr (帶弟弟ocr)函式庫是一個簡單實用的辨識驗證碼的函式庫,推薦給大家

ddddocr具體使用方法

import os
import ddddocr
from time import sleep
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By

class GetVerificationCode:
	def __init__(self):
        self.res = None
        url = '要登录的地址'
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()  # 将浏览器最大化
        self.driver.get(url)

	# 获取验证码信息
    def getVerification(self):
        # 获取当前文件的位置、并获取保存截屏的位置
        current_location = os.path.dirname(__file__)
        screenshot_path = os.path.join(current_location, "..", "VerificationCode")
        # 截取当前网页并放到自定义目录下,并命名为printscreen,该截图中有我们需要的验证码
        sleep(1)
        self.driver.save_screenshot(screenshot_path + '//' + 'printscreen.png')
        sleep(1)
        # 定位验证码
        imgelement = self.driver.find_element(By.XPATH, '验证码图片的Xpath定位')
        # 获取验证码x,y轴坐标
        location = imgelement.location
        # 获取验证码的长宽
        size = imgelement.size
        # 写成我们需要截取的位置坐标
        rangle = (int(location['x'] + 430),
                  int(location['y'] + 200),
                  int(location['x'] + size['width'] + 530),
                  int(location['y'] + size['height'] + 250))
        # 打开截图
        i = Image.open(screenshot_path + '//' + 'printscreen.png')
        # 使用Image的crop函数,从截图中再次截取我们需要的区域
        fimg = i.crop(rangle)
        fimg = fimg.convert('RGB')
        # 保存我们截下来的验证码图片,并读取验证码内容
        fimg.save(screenshot_path + '//' + 'code.png')
        ocr = ddddocr.DdddOcr()
        with open(screenshot_path + '//' + 'code.png', 'rb') as f:
            img_bytes = f.read()
        self.res = ocr.classification(img_bytes)
        print('识别出的验证码为:' + self.res)

    # 判断验证码错误时的提示信息是否存在
    def isElementPresent(self, by, value):
        try:
            element = self.driver.find_element(by=by, value=value)
        except NoSuchElementException:
            pass
            # 发生了NoSuchElementException异常,说明页面中未找到该元素,返回False
            return False
        else:
            # 没有发生异常,表示在页面中找到了该元素,返回True
            return True

	# 登录
    def login(self):
        self.getVerification()
        self.driver.find_element(By.XPATH, '用户名输入框Xpath定位').send_keys('用户名')
        self.driver.find_element(By.XPATH, '密码输入框Xpath定位').send_keys('密码')
        self.driver.find_element(By.XPATH, '验证码输入框Xpath定位').send_keys(self.res)
        sleep(1)
        self.driver.find_element(By.XPATH, '登录按钮Xpath定位').click()
        sleep(2)
		isFlag = True
        while isFlag:
            try:
                isPresent = self.isElementPresent(By.XPATH, '验证码错误时的提示信息Xpath定位')
                if isPresent is True:
                    codeText = self.driver.find_element(By.XPATH, '验证码错误时的提示信息Xpath定位').text
                    if codeText == "验证码不正确":
                        self.getVerification()
                        sleep(2)
                        self.driver.find_element(By.XPATH, '验证码输入框Xpath定位').clear()
                        sleep(1)
                        self.driver.find_element(By.XPATH, '验证码输入框Xpath定位').send_keys(self.res)
                        sleep(1)
                        self.driver.find_element(By.XPATH, '登录按钮Xpath定位').click()
                        sleep(2)
                    tips = self.driver.find_element(By.XPATH,
                                                    '未输入验证码时的提示信息Xpath定位').text
                    if tips == "请输入验证码":
                        self.getVerification()
                        sleep(2)
                        self.driver.find_element(By.XPATH, '验证码输入框Xpath定位').click()
                        sleep(1)
                        self.driver.find_element(By.XPATH, '验证码输入框Xpath定位').send_keys(self.res)
                        sleep(1)
                        self.driver.find_element(By.XPATH, '登录按钮Xpath定位').click()
                        sleep(2)
                    continue
                else:
                    print("验证码正确,登录成功!")
            except NoSuchElementException:
                pass
            else:
                isFlag = False
                
        sleep(5)
        self.driver.quit()


if __name__ == '__main__':
    GetVerificationCode().login()

識別結果

Python怎麼實現取得網頁內容及自動填表單與登入功能

#

以上是Python怎麼實現取得網頁內容及自動填表單與登入功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
Numpy數組與使用數組模塊創建的數組有何不同?Numpy數組與使用數組模塊創建的數組有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模塊與Python中的數組有何關係?CTYPES模塊與Python中的數組有何關係?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

在Python的上下文中定義'數組”和'列表”。在Python的上下文中定義'數組”和'列表”。Apr 24, 2025 pm 03:41 PM

Inpython,一個“列表” isaversatile,mutableSequencethatCanholdMixedDatateTypes,而“陣列” isamorememory-sepersequeSequeSequeSequeSequeRingequiringElements.1)列表

Python列表是可變還是不變的?那Python陣列呢?Python列表是可變還是不變的?那Python陣列呢?Apr 24, 2025 pm 03:37 PM

pythonlistsandArraysareBothable.1)列表Sareflexibleandsupportereceneousdatabutarelessmory-Memory-Empefficity.2)ArraysareMoremoremoremoreMemoremorememorememorememoremorememogeneSdatabutlesserversEversementime,defteringcorcttypecrecttypececeDepeceDyusagetoagetoavoavoiDerrors。

Python vs. C:了解關鍵差異Python vs. C:了解關鍵差異Apr 21, 2025 am 12:18 AM

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

Python vs.C:您的項目選擇哪種語言?Python vs.C:您的項目選擇哪種語言?Apr 21, 2025 am 12:17 AM

選擇Python還是C 取決於項目需求:1)如果需要快速開發、數據處理和原型設計,選擇Python;2)如果需要高性能、低延遲和接近硬件的控制,選擇C 。

達到python目標:每天2小時的力量達到python目標:每天2小時的力量Apr 20, 2025 am 12:21 AM

通過每天投入2小時的Python學習,可以有效提升編程技能。 1.學習新知識:閱讀文檔或觀看教程。 2.實踐:編寫代碼和完成練習。 3.複習:鞏固所學內容。 4.項目實踐:應用所學於實際項目中。這樣的結構化學習計劃能幫助你係統掌握Python並實現職業目標。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。