简单的验证码解决方案

2024-05-21 06:25:23 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在网上寻找破译验证码的方法时,我甚至看不到一个好的例子。

我已经创建了一个非常基本的验证码页面。http://145.100.108.148/login3/

有没有人用一个有效的例子来解决这个问题,或者至少以一种体面的方式配置Scrapy来解决这个问题。


Tags: 方法http方式页面验证码例子scrapy人用
3条回答

下面是一个很好的解决方案

best = ("https://my captcha url")
f = open('captcha.jpg','wb')
f.write(urllib.urlopen(best).read())
f.close()

import pytesseract
import cv2
import pytesseract
from PIL import Image

from pdf2image import convert_from_path
#img = Image.open('captcha.jpg')
image = cv2.imread('captcha.jpg')

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

#gray = cv2.medianBlur(gray, 3)

filename = "{}.png".format("temp")
cv2.imwrite(filename, gray)
text = pytesseract.image_to_string(Image.open('temp.png'))
print text

https://www.imagetyperz.com/Forms/api/api.html您可以检查他们的captcha solver api。它们可以绕过所有类型的验证码,包括recaptcha v2

使用PillowPython Tesseract很容易解决验证码本身。困难的部分是如何处理cookies(PHPSESSID)。下面是您的案例的完整工作示例(使用Python 2):

# -*- coding: utf-8 -*-                                                         
import io                                                                       
import urllib2                                                                  

from PIL import Image                                                           
import pytesseract                                                              
import scrapy                                                                   


class CaptchaSpider(scrapy.Spider):                                             
    name = 'captcha'                                                            

    def start_requests(self):                                                   
        yield scrapy.Request('http://145.100.108.148/login3/',                  
                             cookies={'PHPSESSID': 'xyz'})                      

    def parse(self, response):                                                  
        img_url = response.urljoin(response.xpath('//img/@src').extract_first())

        url_opener = urllib2.build_opener()                                     
        url_opener.addheaders.append(('Cookie', 'PHPSESSID=xyz'))               
        img_bytes = url_opener.open(img_url).read()                             
        img = Image.open(io.BytesIO(img_bytes))                                 

        captcha = pytesseract.image_to_string(img)                              
        print 'Captcha solved:', captcha                                        

        return scrapy.FormRequest.from_response(                                
            response, formdata={'captcha': captcha},                            
            callback=self.after_captcha)                                        

    def after_captcha(self, response):                                          
        print 'Result:', response.body

相关问题 更多 >