Scrapy模拟登陆知乎

作者: mylonly | 来源:发表于2016-05-30 17:41 被阅读1665次

知乎新版登陆已经增加了验证码,此文章不再适用

感谢简书作者Andrew_liu提供的思路,虽然知乎改版后,该文章上提供的方法已经失效Python爬虫(七)--Scrapy模拟登录

利用Scrapy提供的cookie中间价很容易做到网页的模拟登陆,下面就来介绍怎么利用这个cookie中间件来登陆知乎。

###****前期分析工作

  • 打开https://www.zhihu.com,利用Chrome浏览器的Debug功能,定位到登陆框所在的位置,如下图所示


    利用scrapy提供的xpath能很方便的获取到这个值(//div[@data-za-module="SignInForm"]//form//input[@name="_xsrf"]/@value')
  • 选中Debug窗口的Network选项,同时在输完账号密码后点击登陆,获取登陆操作后的post请求,见下图:

注意:由于知乎页面在登录成功后会跳转到新的页面,所以使用debug中的 >network功能获取数据包时一定要在登录后快速的将recording按钮停止掉(上图左上角那个黑色的圆圈按钮,recoding状态时红色,黑色是stop recording状态),否则登录的报文就没了。

点击这个链接,确认这个链接就是提交登陆的url


从FormData里面可以看到https://www.zhihu.com/email/login就是登陆POST请求的url,需要提交4个参数,其中_xsrf就是首页可以获取到的隐藏表单参数,remember_me是是否记住cookie的开关,email和password对应账号和密码

此处可能有不一样的地方,因为我的知乎账号是email注册的,根据这个url的特征推测别的账号类型可能存在不一样的Url

### ****编写蜘蛛代码
1.继承CrawlSpider,并重写spider的start_request方法,让spier先访问登录页再去爬取start_urls中的链接,在start_requests方法中,让spider先去访问知乎首页,去获取隐藏的表单项_xsrf

def start_requests(self):
        return [Request("https://www.zhihu.com/",headers = self.headers,meta={"cookiejar":1},callback=self.post_login)]

其中header需要自定义,因为知乎对spider做了限制,应该是检测User-Agent,你可以在setting.py中更改spider的默认UserAgent,也可以像我这样自己自定义一个

headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Encoding": "gzip,deflate",
    "Accept-Language": "en-US,en;q=0.8,zh-TW;q=0.6,zh;q=0.4",
    "Connection": "keep-alive",
    "Content-Type":" application/x-www-form-urlencoded; charset=UTF-8",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36",
    "Referer": "http://www.zhihu.com"
}

meta中的cookiejar是Scrapy的Cookie中间件的关键字,具体可参考scrapy文档,这里因为只需要保存一个cookie,所以直接写1(注意:并不是1个cookie才写的1,仅仅是个key,后面通过这个1这个key找到cookiejar中保存的cookie)

2.解析首页内容,获取到_xsrf的值,同时提交登录请求:

def post_login(self,response):
        self.log("preparing login...")
        xsrf = Selector(response).xpath('//div[@data-za-module="SignInForm"]//form//input[@name="_xsrf"]/@value').extract()[0]
        self.log(xsrf)
        return FormRequest("https://www.zhihu.com/login/email",meta={'cookiejar':1},
                                          headers = self.headers,
                                          formdata = {
                                             '_xsrf':xsrf,
                                             'password':'xxxxxxx',
                                             'email':'xxx@gmail.com',
                                             'remember_me':'true',
                                          },
                                          callback = self.after_login,
                                          )
  1. 将登录成功后获取到的cookie传递给每一个start_urls中链接的ruquest
def after_login(self,response):
        for url in self.start_urls:
            yield Request(url,meta={'cookiejar':1},headers = self.headers)

4.由于cookiejar中的cookie并不会自动发送给每个链接,因此在urls通过Rule获取到的连接,也是需要我们手动将cookie加上,通过Rule提供的process_request参数重新创建带cookie的Request

rules = (
        Rule(SgmlLinkExtractor(allow=('/question/\\d*')),process_request="request_question"),
    )

同时提供request_question函数

def request_question(self,request):
        return Request(request.url,meta={'cookiejar':1},headers = self.headers,callback=self.parse_question)

5.由于已经有了process_link ,Rule中的callback参数就不再起作用了,而是调用新构造的Request中的callback函数。

def parse_question(self,response):
        sel = Selector(response)
        item = zhihuItem()
        item['qestionTitle'] = sel.xpath("//div[@id='zh-question-title']//h2/text()").extract_first()
        item['image_urls'] = sel.xpath("//img[@class='origin_image zh-lightbox-thumb lazy']/@data-original").extract()
        return item

这个parse_question方法仅仅是获取问题名称和问题下面的所有图片链接。

### ****完整代码

import urllib2
import os
import re
import codecs

from scrapy.contrib.spiders import CrawlSpider,Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from MySpider.items import zhihuItem
from scrapy.http import Request
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser

class zhihuSpider(CrawlSpider):
    name = "zhihu"
    allow_domians = ["zhihu.com"]
    start_urls = ["https://www.zhihu.com/collection/38624707"]
    rules = (
        Rule(SgmlLinkExtractor(allow=('/question/\\d*')),process_request="request_question"),
    )
    
    headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Encoding": "gzip,deflate",
    "Accept-Language": "en-US,en;q=0.8,zh-TW;q=0.6,zh;q=0.4",
    "Connection": "keep-alive",
    "Content-Type":" application/x-www-form-urlencoded; charset=UTF-8",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36",
    "Referer": "http://www.zhihu.com"
    }
    
    def start_requests(self):
        return [Request("https://www.zhihu.com/",headers = self.headers,meta={"cookiejar":1},callback=self.post_login)]
        
    def post_login(self,response):
        self.log("preparing login...")
        xsrf = Selector(response).xpath('//div[@data-za-module="SignInForm"]//form//input[@name="_xsrf"]/@value').extract()[0]
        self.log(xsrf)
        return FormRequest("https://www.zhihu.com/login/email",meta={'cookiejar':response.meta['cookiejar']},
                                          headers = self.headers,
                                          formdata = {
                                             '_xsrf':xsrf,
                                             'password':'差点就忘了删了',
                                             'email':'邮箱也不能暴露',
                                             'remember_me':'true',
                                          },
                                          callback = self.after_login,
                                          )
                                                      
    def after_login(self,response):
        for url in self.start_urls:
            yield Request(url,meta={'cookiejar':1},headers = self.headers)
   
    def request_question(self,request):
        return Request(request.url,meta={'cookiejar':1},headers = self.headers,callback=self.parse_question)
        
    def parse_question(self,response):
        sel = Selector(response)
        item = zhihuItem()
        item['qestionTitle'] = sel.xpath("//div[@id='zh-question-title']//h2/text()").extract_first()
        item['image_urls'] = sel.xpath("//img[@class='origin_image zh-lightbox-thumb lazy']/@data-original").extract()
        return item

相关文章

  • 模拟登陆存在问题

    学习Python爬虫(七)--Scrapy模拟登录的post模拟登陆后,自己写了模拟登陆知乎首页的代码。 测试后发现无效

  • Scrapy模拟登陆知乎

    知乎新版登陆已经增加了验证码,此文章不再适用 感谢简书作者Andrew_liu提供的思路,虽然知乎改版后,该文章上...

  • python模拟登录练习(一)

    上一篇文章模拟登陆存在问题用scrapy无法登录知乎,后来志明S告诉我是验证码的问题,另外知乎上xchaoinfo...

  • Scrapy 1.4 + Python 3.6模拟登陆知乎

    最近学习Python爬虫,用到了Scrapy这个爬虫框架。目前Scrapy的最新版本已经达到了Scrapy 1.4...

  • 模拟登陆知乎

    原因 为啥要写这一篇文章呢?(主要是qq群内有人在模拟登陆知乎,一直不成功)然后我抓包看了下,发现知乎登陆页已经改...

  • 知乎模拟登陆

    经常在简书上写作,写完后再发布到其他网站,非常麻烦,所以准备搞一下自动发布文章的工具。那么第一步先要模拟登陆几个网...

  • 模拟登陆知乎

    一、开始抓包 首先内,还是打开知乎首页,然后输入账号密码,登陆(记得输错密码) 这样我们就可以看到请求头了(请求头...

  • scrapy模拟登陆知乎--抓取热点话题

    折腾了将近两天,中间数次想要放弃,还好硬着头皮搞下去了,在此分享出来,希望有同等需求的各位能少走一些弯路。源码放在...

  • scrapy模拟登陆知乎--抓取热点话题

    工具准备 在开始之前,请确保scrpay正确安装,手头有一款简洁而强大的浏览器, 若是你有使用postman那就更...

  • Scrapy 模拟登录新版知乎

    写这篇文章是因为知乎登录已经改版了,新版登录和老版登录区别还是挺大了,新版登录的 post 请求减少了一些字段的同...

网友评论

  • louyw:你没有处理验证码么?
    mylonly:@louyw 之前版本没有验证码,评论中有人给出了新的解决方案
  • Reborn_L:现在第一次登录完,退出再登录,会出现图片验证码,post参数会多出两个新的字段captcha:{"img_size":[200,44],"input_points":[[45.9375,32],[166.938,24]]}和captcha_type:cn:cold_sweat:
    mundane:@mylonly 已找到解决方案, 手机端网页登录没有倒立文字的验证, 把User-Agent改成手机浏览器的User-Agent。具体请参照https://github.com/xchaoinfo/fuck-login/blob/master/001%20zhihu/zhihu.py
    mylonly:@mundane 暂时还没有好的办法,这种验证码我也没处理过:sleepy:
    mundane:对啊, 求问, 这个怎么解决啊?
  • Reborn_L:为什么我感觉response中有个方法是css(封装了一下xpath的功能),感觉这个更好用:joy:
  • 0091c7bc766f:这个spider只能爬一个页面吧?没看出来它是怎么跳转到更多页面去爬的。
    mylonly:@Lucas_琛 恩 :smile:, 谢谢打赏支持!!!
    0091c7bc766f:@mylonly 嗯嗯,刚开始看scrapy。原来spider会主动扫描页面找符合rules的页面去爬,我还以为要手写一个recursion的。难怪都推荐用scrapy,方便很多!
    mylonly:@Lucas_琛 crawlSpider根据Rules中的正则去跟进新的url
  • 0091c7bc766f:写得清楚易懂,点赞!另外,知乎妹子爆照大合集...看了此文才知道的,额外的收获!
  • 35c016ab5734:感谢作者 :kissing_heart:
    然而你还是在注释_xsrf的时候,暴露了邮箱和密码。
    mylonly:@流小火 😩,已经编辑掉了,谢谢提醒
  • xXPzXj:想问个问题。
    html代码是:
    <a>怒海争霸</a>
    <a>第1部</a>
    <a>第2部</a>
    <a>第3部</a>
    <a>第4部</a>

    我想要的是 内容是 “第”开头的那几个a标签,要怎么写xpath啊,我查了半天写了一个:
    k = '第'
    a[contains(.//text(),k)]
    但是不对啊
    mylonly:@某小HAO //a[contains(.//text(),'HAO')]//text() 我这样是可以的啊

本文标题:Scrapy模拟登陆知乎

本文链接:https://www.haomeiwen.com/subject/yjhcdttx.html