Scrapy爬虫Response子类在应用中的问题解析

 更新时间:2023年05月16日 14:35:53   作者:ponponon  
这篇文章主要为大家介绍了Scrapy爬虫Response它的子类(TextResponse、HtmlResponse、XmlResponse)在应用问题解析

正文

今天用scrapy爬取壁纸的时候(url:http://pic.netbian.com/4kmein...)絮叨了一些问题,记录下来,供后世探讨,以史为鉴。**

因为网站是动态渲染的,所以选择scrapy对接selenium(scrapy抓取网页的方式和requests库相似,都是直接模拟HTTP请求,而Scrapy也不能抓取JavaScript动态渲染的网页。)

所以在Downloader Middlewares中需要得到Request并且返回一个Response,问题出在Response,通过查看官方文档发现class scrapy.http.Response(url[, status=200, headers=None, body=b'', flags=None, request=None]),随即通过from scrapy.http import Response导入Response

输入scrapy crawl girl得到如下错误:

*results=response.xpath('//[@id="main"]/div[3]/ul/lia/img')
raise NotSupported("Response content isn't text")
scrapy.exceptions.NotSupported: Response content isn't text**

检查相关代码:

# middlewares.py
from scrapy import signals
from scrapy.http import Response
from scrapy.exceptions import IgnoreRequest
import selenium
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class Pic4KgirlDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.
    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.
        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        try:
            self.browser=selenium.webdriver.Chrome()
            self.wait=WebDriverWait(self.browser,10)
            self.browser.get(request.url)
            self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#main > div.page > a:nth-child(10)')))
            return Response(url=request.url,status=200,request=request,body=self.browser.page_source.encode('utf-8'))
        #except:
            #raise IgnoreRequest()
        finally:
            self.browser.close()

推断问题出在:

return Response(url=request.url,status=200,request=request,body=self.browser.page_source.encode('utf-8'))

查看Response类的定义

@property
    def text(self):
        """For subclasses of TextResponse, this will return the body
        as text (unicode object in Python 2 and str in Python 3)
        """
        raise AttributeError("Response content isn't text")
    def css(self, *a, **kw):
        """Shortcut method implemented only by responses whose content
        is text (subclasses of TextResponse).
        """
        raise NotSupported("Response content isn't text")
    def xpath(self, *a, **kw):
        """Shortcut method implemented only by responses whose content
        is text (subclasses of TextResponse).
        """
        raise NotSupported("Response content isn't text")

说明Response类不可以被直接使用,需要被继承重写方法后才能使用

响应子类

**TextResponse对象**
class scrapy.http.TextResponse(url[, encoding[, ...]])
**HtmlResponse对象**
class scrapy.http.HtmlResponse(url[, ...])
**XmlResponse对象**
class scrapy.http.XmlResponse(url [,... ] )

举例观察TextResponse的定义from scrapy.http import TextResponse

导入TextResponse发现

class TextResponse(Response):
    _DEFAULT_ENCODING = 'ascii'
    def __init__(self, *args, **kwargs):
        self._encoding = kwargs.pop('encoding', None)
        self._cached_benc = None
        self._cached_ubody = None
        self._cached_selector = None
        super(TextResponse, self).__init__(*args, **kwargs)

其中xpath方法已经被重写

@property
    def selector(self):
        from scrapy.selector import Selector
        if self._cached_selector is None:
            self._cached_selector = Selector(self)
        return self._cached_selector
    def xpath(self, query, **kwargs):
        return self.selector.xpath(query, **kwargs)
    def css(self, query):
        return self.selector.css(query)

所以用户想要调用Response类,必须选择调用其子类,并且重写部分方法

Scrapy爬虫入门教程十一 Request和Response(请求和响应)

scrapy文档:https://doc.scrapy.org/en/lat...

中文翻译文档:https://www.jb51.net/article/248161.htm

以上就是Scrapy爬虫Response子类在应用中的问题解析的详细内容,更多关于Scrapy爬虫Response子类应用的资料请关注脚本之家其它相关文章!

相关文章

  • Python采集王者最低战力信息实战示例

    Python采集王者最低战力信息实战示例

    这篇文章主要为大家介绍了Python采集王者最低战力信息实战示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-04-04
  • miniconda3介绍、安装以及使用教程

    miniconda3介绍、安装以及使用教程

    Miniconda是一款小巧的python环境管理工具,安装包大约只有50M多点,其安装程序中包含conda软件包管理器和Python,下面这篇文章主要给大家介绍了关于miniconda3介绍、安装以及使用的相关资料,需要的朋友可以参考下
    2023-02-02
  • python 实现数组list 添加、修改、删除的方法

    python 实现数组list 添加、修改、删除的方法

    下面小编就为大家分享一篇python 实现数组list 添加、修改、删除的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-04-04
  • 人工智能Text Generation文本生成原理示例详解

    人工智能Text Generation文本生成原理示例详解

    这篇文章主要为大家介绍了Text Generation文本生成原理示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-01-01
  • Python实现统计代码行的方法分析

    Python实现统计代码行的方法分析

    这篇文章主要介绍了Python实现统计代码行的方法,结合实例形式分析了Python针对代码行数的计算实现步骤与操作技巧,需要的朋友可以参考下
    2017-07-07
  • 基于python调用psutil模块过程解析

    基于python调用psutil模块过程解析

    这篇文章主要介绍了基于python调用psutils模块过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • Python多进程原理与用法分析

    Python多进程原理与用法分析

    这篇文章主要介绍了Python多进程原理与用法,结合实例形式分析了Python多进程原理、开启使用进程、进程队列、进程池等相关概念与使用方法,需要的朋友可以参考下
    2018-08-08
  • python实战之百度智能云使人像动漫化

    python实战之百度智能云使人像动漫化

    这篇文章主要介绍了python实战之百度智能云使人像动漫化,文中有非常详细的代码示例,对正在学习python的小伙伴们有很好地帮助,需要的朋友可以参考下
    2021-04-04
  • 人工智能学习PyTorch实现CNN卷积层及nn.Module类示例分析

    人工智能学习PyTorch实现CNN卷积层及nn.Module类示例分析

    这篇文章主要为大家介绍了人工智能学习PyTorch实现CNN卷积层及nn.Module类示例分析,有需要的朋友可以借鉴参考下,希望能够有所帮助
    2021-11-11
  • 详解Python遍历字典的键和值

    详解Python遍历字典的键和值

    这篇文章主要通过一些简单的示例为大家介绍一下Python中遍历字典的键和值的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2023-03-03

最新评论