Module scrapfly.scrapy.request

Classes

class ScrapflyScrapyRequest (scrape_config: ScrapeConfig,
meta: Dict | None = None,
*args,
**kwargs)
Expand source code
class ScrapflyScrapyRequest(Request):
    scrape_config: ScrapeConfig

    # See request_from_dict method in scrapy.utils.request
    attributes = tuple(
        attr for attr in Request.attributes if attr not in ["body", "cookies", "headers", "method", "url"]) + (
                 "scrape_config",)

    # url:str   inherited
    # method:str inherited
    # body:bytes inherited
    # headers:Dict inherited
    # encoding:Dict inherited

    def __init__(self, scrape_config: ScrapeConfig, meta: Optional[Dict] = None, *args, **kwargs): 
        self.scrape_config = scrape_config

        if meta is None:
            meta = {}

        meta['scrapfly_scrape_config'] = self.scrape_config

        super().__init__(
            *args,
            url=self.scrape_config.url,
            headers=self.scrape_config.headers,
            cookies=self.scrape_config.cookies,
            body=self.scrape_config.body,
            meta=meta,
            **kwargs
        )

    def to_dict(self, *, spider: Optional["scrapy.Spider"] = None) -> dict:
        if spider is None:
            raise ValueError("The 'spider' argument is required to serialize the request.")
        d = super().to_dict(spider=spider)
        d['scrape_config'] = self.scrape_config
        return d

    @classmethod
    def from_dict(cls, data):
        scrape_config_data = data['meta']['scrapfly_scrape_config'].to_dict()
        scrape_config = ScrapeConfig.from_dict(scrape_config_data)
        request = cls(scrape_config=scrape_config)
        return request

    def replace(self, *args, **kwargs):
        for x in [
            'meta',
            'flags',
            'encoding',
            'priority',
            'dont_filter',
            'callback',
            'errback',
            'cb_kwargs',
        ]:
            kwargs.setdefault(x, getattr(self, x))
            kwargs['scrape_config'] = deepcopy(self.scrape_config)

        cls = kwargs.pop('cls', self.__class__)
        return cls(*args, **kwargs)

Represents an HTTP request, which is usually generated in a Spider and executed by the Downloader, thus generating a :class:~scrapy.http.Response.

url is the URL of the request. If it is invalid, :exc:ValueError is raised.

method is the HTTP method of the request.

headers are the request headers. Header values can be strings, for single-valued headers, or lists, for multi-valued headers. Headers with a None value are not sent.

Caution: The :ref:cookie middleware <cookies> ignores cookies set

through the Cookie header. Use cookies instead.

body is the request body. A string body is encoded with encoding.

cookies are the request cookies, as a dict of cookie names and values or as a list of dicts with a cookie each. See :ref:cookies.

encoding is used to percent-encode url, unless the :reqmeta:verbatim_url request meta key is set, and to encode body if it is a string.

flags is a list of labels for the request, which are included in log messages about it.

meta and cb_kwargs are shallow copied into :attr:meta and :attr:cb_kwargs.

callback, errback, priority, dont_filter and parent_id set the attributes of the same name. Set parent_id when building a request on behalf of another request, e.g. in a downloader middleware: Request(url, parent_id=request.id).

Ancestors

  • scrapy.http.request.Request
  • scrapy.utils.trackref.object_ref

Class variables

var attributes : tuple[str, ...]
var scrape_config : ScrapeConfig

Static methods

def from_dict(data)

Methods

def replace(self, *args, **kwargs)
Expand source code
def replace(self, *args, **kwargs):
    for x in [
        'meta',
        'flags',
        'encoding',
        'priority',
        'dont_filter',
        'callback',
        'errback',
        'cb_kwargs',
    ]:
        kwargs.setdefault(x, getattr(self, x))
        kwargs['scrape_config'] = deepcopy(self.scrape_config)

    cls = kwargs.pop('cls', self.__class__)
    return cls(*args, **kwargs)

Return a new request with the same attributes as this one, except for those given new values as keyword arguments named after :attr:attributes.

:attr:cb_kwargs and :attr:meta are :doc:shallow copied <library/copy> unless given new values. The new request gets a new :attr:id, and :attr:parent_id defaults to the :attr:id of this request. cls sets the class of the new request.

See also :ref:callback-data.

def to_dict(self, *, spider: ForwardRef('scrapy.Spider') | None = None) ‑> dict
Expand source code
def to_dict(self, *, spider: Optional["scrapy.Spider"] = None) -> dict:
    if spider is None:
        raise ValueError("The 'spider' argument is required to serialize the request.")
    d = super().to_dict(spider=spider)
    d['scrape_config'] = self.scrape_config
    return d

Return a dictionary containing the Request's data.

Use :func:~scrapy.utils.request.request_from_dict to convert back into a :class:~scrapy.Request object.

If a spider is given, this method will try to find out the name of the spider methods used as callback and errback and include them in the output dict, raising an exception if they cannot be found.