


How to implement the functions of obtaining web page content and automatically filling in forms and logging in using Python
Library
import time import ddddocr
Source code
# 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("登陆: 提交表单")
Knowledge point supplement
The following will introduce the related use of the dddddocr library used in the article
Identification There are many Python libraries for verification codes, and they are not easy to use. The ddddocr (with brother ocr) library is a simple and practical library for identifying verification codes. I recommend you to use
dddddocr.
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()
Recognition result
The above is the detailed content of How to implement the functions of obtaining web page content and automatically filling in forms and logging in using Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
