加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Scrapy&captcha

发布时间:2020-12-20 13:47:10 所属栏目:Python 来源:网络整理
导读:我在网站 https://www.barefootstudent.com/jobs中使用scrapy提交表格(任何链接到页面,等等 http://www.barefootstudent.com/los_angeles/jobs/full_time/full_time_nanny_needed_in_venice_217021) 我的scapy机器人成功登录但我无法避免验证码. 对于表单提
我在网站 https://www.barefootstudent.com/jobs中使用scrapy提交表格(任何链接到页面,等等 http://www.barefootstudent.com/los_angeles/jobs/full_time/full_time_nanny_needed_in_venice_217021)

我的scapy机器人成功登录但我无法避免验证码.
对于表单提交,我使用scrapy.FormRequest.from_reponse

frq = scrapy.FormRequest.from_response(response,formdata={'message': 'itttttttt','security': captcha,'name': 'fx','category_id': '2','email': 'ololo%40gmail.com','item_id': '216640_2','location': '18','send_message': 'Send%20Message'
                                   },callback=self.afterForm)

    yield frq

我想从这个页面加载验证码图像,并手动输入到脚本运行时.
等等

captcha = raw_input("put captcha in manually>")

我试试

urllib.urlretrieve(captcha,"./captcha.jpg")

但是这种方法加载不正确的验证码(网站拒绝我的输入).我尝试在一个运行脚本中反复调用urllib.urlretieve,每次他返回不同的验证码:(

之后,我尝试使用ImagePipeline.
但我的问题是返回项目(下载图像)只在函数完成执行后才会发生,即使我使用了yeild.

item = BfsItem()
 item['image_urls'] = [captcha]
 yield item
 captcha = raw_input("put captcha in manually>")  
 frq = scrapy.FormRequest.from_response(response,callback=self.afterForm)
 yield frq

那一刻,当我的脚本请求输入时,图片没有下载!

如何修改我的脚本,并可以在手动输入验证码后调用FormRequest?

非常感谢你!

解决方法

我正在使用的方法通常效果很好看起来像这样(只需要一个要点,你需要添加你的具体细节):

第1步 – 获取验证码网址(并保留表单的响应以供日后使用)

def parse_page_with_captcha(response):
    captcha_url = response.xpath(...)
    data_for_later = {'captcha_form': response} # store the response for later use
    return Request(captcha_url,callback=self.parse_captcha_download,meta=data_for_later)

第2步 – 现在scrapy将下载图像,我们必须在scrapy回调中正确处理它

def parse_captcha_download(response):
    captcha_target_filename = 'filename.png'
    # save the image for processing
    i = Image.open(StringIO(response.body))
    i.save(captcha_target_filename)

    # process the captcha (OCR,or sending it to a decaptcha service,etc ...)
    captcha_text = solve_captcha(captcha_target_filename)

    # and now we have all the data we need for building the form request
    captcha_form = response.meta['captcha_form']

    return scrapy.FormRequest.from_response(captcha_form,'security': captcha_text,'send_message': 'Send%20Message'
                               },callback=self.afterForm)

重要细节

Captcha受保护的表单需要某种方式将验证码图像与查看和回答此验证码的特定用户/客户端相关联.这通常使用基于cookie的会话或隐藏在验证码表单中的特殊参数/图像标记来完成.

刮刀代码必须小心,不要破坏此链接,否则它将回答一些验证码,但不是它必须的验证码.

为什么不使用Verz1Lka发布的两个例子呢?

urllib.urlretrieve方法完全在scrapy之外工作.虽然这通常是一个坏主意(这不会使用scrapys调度等的好处),但主要问题是:此请求将完全在目标站点用于跟踪哪些会话cookie,url参数等之外工作验证码被发送到特定的浏览器.

另一方面,使用图像管道的方法在Scrapy规则中很好地播放,但是这些图像下载计划在稍后进行,因此在需要时将无法获得验证码下载.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读