scrapy打造知乎后花园一: 验证码登录

来源:互联网 发布:游戏编程需要怎么学 编辑:程序博客网 时间:2024/05/21 19:31

总体思路:

1.找到生成验证码图片的网址。

2.显示有验证码的图片,手动输入验证码。

3.发送用户名,密码,验证码等数据到知乎验证服务器。

4.验证是否登录成功。

第一步:网页采集前的分析和找到验证码的网址。

1.使用工具Google Chrome浏览器打开www.zhihu.com,按F12打开调试工具,选择Network。

   随便输入用户名和密码,找到phone_num,点Response,看到"r":1表示登录失败,0表示成功。




2.选择Headers,Form Data 可以看到登录提交表单数据,Request Headers可以看到cookie等信息。


3.从Form Data可以看出,验证表单时,除了用户名,密码,还要提交_xsrf。

    

4.多输几次错误密码,就会要求输入验证码。点Img,选择Preview找到验证码。



5、再选择Headers,就找到了验证码的图片地址:为了方便测试,将lang=cn改为lang=en。r=1500340819993为时间戳。

https://www.zhihu.com/captcha.gif?r=1500340819993&type=login&lang=cn



[root@master ~]# scrapy startproject zhihu

[root@master zhihu]# scrapy genspider -t basic myspider zhihu.com

第二步:代码分析myspider.py。

# -*- coding: utf-8 -*-import scrapyfrom scrapy.http import Request, FormRequestfrom zhihu.items import *import timefrom PIL import Imageimport jsonclass MyspiderSpider(scrapy.Spider):    name = 'myspider'    allowed_domains = ['zhihu.com']    start_urls = ['https://www.zhihu.com/']    def start_requests(self):        t = str(int(time.time() * 1000))        captcha_url = 'https://www.zhihu.com/captcha.gif?r=' + t + '&type=login&lang=en'        return [Request(captcha_url, callback=self.parser_captcha)]    def parser_captcha(self, response):        with open('captcha.jpg', 'wb') as f:            f.write(response.body)            f.close()        im = Image.open('captcha.jpg')        im.show()        im.close()        captcha = raw_input("input the captcha with quotation mark\n>")        return Request(url='https://www.zhihu.com/', callback=self.login,meta={'captcha':captcha})        def login(self,response):        xsrf = response.xpath('//input[@name="_xsrf"]/@value').extract()[0]        print 'xsrf:'+ xsrf        print response.meta['captcha']        return [FormRequest('https://www.zhihu.com/login/phone_num',                method='POST',                formdata = {                    'phone_num':'131*******',                    'password':'xyz***',                    '_xsrf':xsrf,                    'captcha_type':'en',                    'captcha':response.meta['captcha'],                },                callback = self.after_login,        )]    def after_login(self,response):        json_file = json.loads(response.text)        if json_file['r'] == 0:            print('success........登录成功')        else:           print('登录失败!')


第三步:代码测试。

[root@master zhihu]# scrapy crawl myspider

1.手动输入验证码。要显示验证码,centos7要安装图形界面,还要需要Pillow库来显示图片。

2.打印xsrf,手动输入的验证码hjfx,显示登录成功。如果验证码输入错误,显示登录失败。

现在已经可以登录知乎了,下一篇可以写继续爬了。。。。。。。

阅读全文
1 0
原创粉丝点击