栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何设置Scrapy来处理验证码

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何设置Scrapy来处理验证码

有很多解决方案是一个非常深入的话题。但是,如果你想应用在帖子中定义的逻辑,则可以使用scrapy Downloader Middlewares。

就像是:

class CaptchaMiddleware(object):    max_retries = 5    def process_response(request, response, spider):        if not request.meta.get('solve_captcha', False): return response  # only solve requests that are marked with meta key        catpcha = find_catpcha(response)        if not captcha:  # it might not have captcha at all! return response        solved = solve_captcha(captcha)        if solved: response.meta['catpcha'] = captcha response.meta['solved_catpcha'] = solved return response        else: # retry page for new captcha # prevent endless loop if request.meta.get('catpcha_retries', 0) == 5:     logging.warning('max retries for captcha reached for {}'.format(request.url))     raise IgnoreRequest  request.meta['dont_filter'] = True request.meta['captcha_retries'] = request.meta.get('captcha_retries', 0) + 1 return request

此示例将拦截每个响应并尝试解决验证码。如果失败,它将重试该页面以获取新的验证码;如果成功,它将添加一些元密钥以响应已解决的验证码值。
在蜘蛛中,你可以这样使用它:

class MySpider(scrapy.Spider):    def parse(self, response):        url = ''# url that requires captcha        yield Request(url, callback=self.parse_captchad, meta={'solve_captcha': True},errback=self.parse_fail)    def parse_captchad(self, response):        solved = response['solved']        # do stuff    def parse_fail(self, response):        # failed to retrieve captcha in 5 tries :(        # do stuff


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/369534.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号