使用Ruby实现文字识别验证码的自动化处理



本文将介绍如何使用Ruby语言来实现文字识别验证码的自动化处理。具体步骤包括提取目标文字和背景图文字,计算点击坐标并模拟点击。

一、目标文字识别
首先,我们需要提取目标文字的图片URL并下载。

ruby

require 'selenium-webdriver'
require 'open-uri'
require 'rmagick'
require 'rtesseract'

# 设置浏览器
driver = Selenium::WebDriver.for :chrome
wait = Selenium::WebDriver::Wait.new(timeout: 10)

# 访问验证码页面
driver.get '验证码页面URL'

# 提取目标文字图片URL并下载
image2 = wait.until { driver.find_element(xpath: '//*[@id="verify-bar-code"]') }
target_img_url = image2.attribute('src')
target_image_content = URI.open(target_img_url).read
File.open('target_image.png', 'wb') { |file| file.write(target_image_content) }

# 使用RTesseract进行OCR识别目标文字
target_image = RTesseract.new('target_image.png')
target_words = target_image.to_s.strip.split('')
二、背景图文字识别
同样地,先提取背景图片的URL并下载。
# 提取背景图片URL并下载
image1 = wait.until { driver.find_element(xpath: '//*[@id="captcha-verify-image"]') }
background_img_url = image1.attribute('src')
background_image_content = URI.open(background_img_url).read
File.open('background_image.png', 'wb') { |file| file.write(background_image_content) }
获取图片后,使用RTesseract库识别背景图文字和位置。

ruby

# 使用RTesseract识别背景图文字和位置
background_image = Magick::Image.read('background_image.png').first
ocr_results = RTesseract.new(background_image)
words_and_positions = ocr_results.words_with_positions
click_identify_result = {}

words_and_positions.each do |word, bounding_box|
  x1, y1, x2, y2 = bounding_box
  click_identify_result[word] = [x1, y1, x2, y2]
end
三、计算点击坐标并点击
文字识别完成后,计算点击坐标并模拟点击。

ruby

# 计算文字点击坐标
img_xy = {}
click_identify_result.each do |word, coords|
  img_xy[word] = [(coords[0] + coords[2]) / 2, (coords[1] + coords[3]) / 2]
end

# 计算最终点击顺序与坐标
result = {}
target_words.each do |word|
  result[word] = img_xy[word]更多内容联系1436423940
end

# 模拟点击
image1_x = image1.location.x
image1_y = image1.location.y
result.each_value do |coords|
  x = coords[0] * (340.0 / 552.0)
  y = coords[1] * (212.0 / 344.0)
  driver.action.move_by(image1_x + x, image1_y + y).click.perform
end

driver.quit

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值