Class: Captcha

Inherits:
Object
  • Object
show all
Defined in:
lib/captcha.rb

Instance Method Summary collapse

Constructor Details

#initialize(requests, solver_details) ⇒ Captcha

Returns a new instance of Captcha.



7
8
9
10
# File 'lib/captcha.rb', line 7

def initialize(requests, solver_details)
  @requests = requests
  @captcha_key = solver_details[:captcha_key]
end

Instance Method Details

#crop_screenshotObject

Crops the screenshot to be mostly just the CAPTCHA



47
48
49
50
51
52
53
# File 'lib/captcha.rb', line 47

def crop_screenshot
  captcha_image = Image.read(@time_name+".png").first
  width = captcha_image.columns
  height = captcha_image.rows
  cropped_captcha = captcha_image.crop(0, 0, width, height/2)
  cropped_captcha.write(@time_name+"_cropped.png")
end

#delete_screenshotsObject

Deletes the screenshot images



56
57
58
# File 'lib/captcha.rb', line 56

def delete_screenshots
  File.delete(@time_name+".png", @time_name+"_cropped.png")
end

#get_captcha_solvedObject

Have the captcha solved



22
23
24
25
26
27
28
29
30
# File 'lib/captcha.rb', line 22

def get_captcha_solved
  client = TwoCaptcha.new(@captcha_key)
  begin
    captcha = client.decode!(file: File.open(@time_name+"_cropped.png"))
  rescue Exception # If it times out
    get_captcha_solved
  end
  return captcha.text
end

#solveObject

Solves the captcha



13
14
15
16
17
18
19
# File 'lib/captcha.rb', line 13

def solve
  take_screenshot
  crop_screenshot
  @captcha_solution = get_captcha_solved
  submit_captcha_solution
  delete_screenshots
end

#submit_captcha_solutionObject

Submit the captcha solution



33
34
35
36
37
38
# File 'lib/captcha.rb', line 33

def submit_captcha_solution
  browser =  @requests.get_most_recent_browser[1][0]
  element = browser.find_element(id: "captcha")
  element.send_keys(@captcha_solution)
  element.submit
end

#take_screenshotObject

Takes a screenshot of captcha in browser



41
42
43
44
# File 'lib/captcha.rb', line 41

def take_screenshot
  @time_name = Time.now.to_s.gsub(" ", "").gsub("-", "").gsub(":", "").gsub("-", "")
  @requests.get_most_recent_browser[1][0].save_screenshot(@time_name+".png")
end