Module scrapfly.async_client

AsyncScrapflyClient: the Scrapfly API over httpx.

Classes

class AsyncScrapflyClient (key: str,
host: str = 'https://api.scrapfly.io',
verify=True,
debug: bool = False,
max_concurrency: int = 1,
connect_timeout: int = 30,
web_scraping_api_read_timeout: int = 160,
extraction_api_read_timeout: int = 165,
screenshot_api_read_timeout: int = 130,
read_timeout: int = 30,
default_read_timeout: int = 30,
reporter: Callable | None = None,
cloud_browser_host: str | None = None,
**kwargs)
Expand source code
class AsyncScrapflyClient(ScrapflyApi):
    """
    The Scrapfly API over httpx. Every operation of ScrapflyApi is a coroutine
    here, and a streamed one an async iterator. Responses are requests.Response
    objects, as with ScrapflyClient.

    Each call opens its own connection unless the client is opened, with
    ``async with AsyncScrapflyClient(...) as client`` or ``await client.open()``.
    """

    def _init_transport(self):
        self._http: Optional[httpx.AsyncClient] = None

    def _new_http(self) -> httpx.AsyncClient:
        return httpx.AsyncClient(verify=self.verify)

    async def open(self):
        if self._http is None:
            self._http = self._new_http()

    async def close(self):
        if self._http is not None:
            await self._http.aclose()
            self._http = None

    async def __aenter__(self) -> 'AsyncScrapflyClient':
        await self.open()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.close()

    @staticmethod
    def _method(steps):
        @wraps(steps)
        async def method(self, *args, **kwargs):
            result = await self._run(steps(self, *args, **kwargs))

            return self._read_stream(result) if isinstance(result, Streamed) else result

        return signed(method, steps, AsyncIterator)

    @staticmethod
    def _stream_method(steps):
        @wraps(steps)
        async def method(self, *args, **kwargs):
            async for item in self._read_stream(await self._run(steps(self, *args, **kwargs))):
                yield item

        return signed(method, steps, AsyncIterator)

    async def _run(self, steps: Steps):
        send, value = steps.send, None

        while True:
            try:
                step = send(value)
            except StopIteration as done:
                return done.value
            except requests.RequestException as error:
                # raise_for_status() prints the request URL, key included.
                masked = without_key(error)
                if masked is error:
                    raise

                raise masked from None

            # Raised inside the operation, at the yield, so its own handlers see it.
            try:
                value, send = await self._perform(step), steps.send
            except BaseException as error:
                value, send = error, steps.throw

    async def _perform(self, step: Call | Sleep) -> Optional[requests.Response]:
        if isinstance(step, Sleep):
            await asyncio.sleep(step.seconds)

            return None

        for attempt in range(step.tries):
            try:
                return await self._send(step)
            except httpx.TransportError as error:
                if attempt + 1 == step.tries:
                    raise

                if isinstance(error, httpx.ReadTimeout) and not step.retry_read_timeout:
                    raise

                await asyncio.sleep(retry_delay(attempt))

    async def _send(self, call: Call) -> requests.Response:
        options = call.options
        # requests encodes the query, the body and the multipart exactly as ScrapflyClient sends them.
        # Session.request drops a header set to None, prepare() alone rejects it.
        prepared = requests.Request(
            method=call.method,
            url=call.url,
            params=options.get('params'),
            headers={name: value for name, value in (options.get('headers') or {}).items() if value is not None},
            data=options.get('data'),
            json=options.get('json'),
            files=options.get('files'),
        ).prepare()
        # httpx then asks for the encodings it can decode.
        prepared.headers.pop('Accept-Encoding', None)

        http = self._http or self._new_http()
        owned = None if http is self._http else http

        try:
            raw = await http.send(
                http.build_request(prepared.method, prepared.url, headers=prepared.headers, content=prepared.body, timeout=_timeout(options.get('timeout'))),
                stream=True,
            )
        except BaseException:
            if owned is not None:
                await owned.aclose()
            raise

        response = requests.Response()
        response.status_code = raw.status_code
        response.reason = raw.reason_phrase
        response.headers = CaseInsensitiveDict(raw.headers.items())
        response.url = str(raw.url)
        response.encoding = get_encoding_from_headers(response.headers)
        response.request = prepared

        # An error body is read whole: the operation reads it as it would a plain response.
        if call.stream and raw.is_success:
            response.raw = _Body(raw, owned)

            return response

        try:
            response._content = await raw.aread()
            response._content_consumed = True
        finally:
            await _Body(raw, owned).aclose()

        return response

    async def _read_stream(self, streamed: Streamed) -> AsyncIterator:
        body: _Body = streamed.response.raw

        try:
            async for chunk in body.raw.aiter_bytes():
                for item in streamed.decoder.feed(chunk):
                    yield item if streamed.finish is None else await self._run(streamed.finish(item))

                if streamed.decoder.done:
                    return

            for item in streamed.decoder.close():
                yield item if streamed.finish is None else await self._run(streamed.finish(item))
        finally:
            await body.aclose()

    async def concurrent_scrape(
        self,
        scrape_configs: List[ScrapeConfig],
        concurrency: Optional[int] = None,
    ) -> AsyncIterator[Union[ScrapeApiResponse, Exception]]:
        """Scrape every config, `concurrency` at a time, and yield each result or error as it completes."""
        if concurrency is None:
            concurrency = self.max_concurrency
        elif concurrency == self.CONCURRENCY_AUTO:
            concurrency = (await self.account())['subscription']['max_concurrency']

        slots = asyncio.Semaphore(concurrency)

        async def scrape(scrape_config: ScrapeConfig):
            scrape_config.raise_on_upstream_error = False

            async with slots:
                try:
                    return await self.scrape(scrape_config)
                except Exception as error:
                    return error

        tasks = [asyncio.ensure_future(scrape(scrape_config)) for scrape_config in scrape_configs]

        try:
            for done in asyncio.as_completed(tasks):
                yield await done
        finally:
            for task in tasks:
                task.cancel()

The Scrapfly API over httpx. Every operation of ScrapflyApi is a coroutine here, and a streamed one an async iterator. Responses are requests.Response objects, as with ScrapflyClient.

Each call opens its own connection unless the client is opened, with async with AsyncScrapflyClient(…) as client or await client.open().

Ancestors

Methods

def account(self) ‑> Steps[str | Dict]
Expand source code
@operation
def account(self) -> Steps[Union[str, Dict]]:
    response = yield Call(
        method='GET',
        url=self.host + '/account',
        params={'key': self.key},
        verify=self.verify,
        headers={
            'accept-encoding': self.body_handler.content_encoding,
            'accept': self.body_handler.accept,
            'user-agent': self.ua
        },
    )

    response.raise_for_status()

    if self.body_handler.support(response.headers):
        return self.body_handler(response.content, response.headers['content-type'])

    return response.content.decode('utf-8')
async def close(self)
Expand source code
async def close(self):
    if self._http is not None:
        await self._http.aclose()
        self._http = None
async def concurrent_scrape(self,
scrape_configs: List[ScrapeConfig],
concurrency: int | None = None) ‑> AsyncIterator[ScrapeApiResponse | Exception]
Expand source code
async def concurrent_scrape(
    self,
    scrape_configs: List[ScrapeConfig],
    concurrency: Optional[int] = None,
) -> AsyncIterator[Union[ScrapeApiResponse, Exception]]:
    """Scrape every config, `concurrency` at a time, and yield each result or error as it completes."""
    if concurrency is None:
        concurrency = self.max_concurrency
    elif concurrency == self.CONCURRENCY_AUTO:
        concurrency = (await self.account())['subscription']['max_concurrency']

    slots = asyncio.Semaphore(concurrency)

    async def scrape(scrape_config: ScrapeConfig):
        scrape_config.raise_on_upstream_error = False

        async with slots:
            try:
                return await self.scrape(scrape_config)
            except Exception as error:
                return error

    tasks = [asyncio.ensure_future(scrape(scrape_config)) for scrape_config in scrape_configs]

    try:
        for done in asyncio.as_completed(tasks):
            yield await done
    finally:
        for task in tasks:
            task.cancel()

Scrape every config, concurrency at a time, and yield each result or error as it completes.

def get_browser_monitoring_metrics(self,
period: str | None = None,
proxy_pool: str | None = None,
start: datetime.datetime | None = None,
end: datetime.datetime | None = None)
Expand source code
@operation
def get_browser_monitoring_metrics(
    self,
    period:Optional[str]=None,
    proxy_pool:Optional[str]=None,
    start:Optional[datetime.datetime]=None,
    end:Optional[datetime.datetime]=None,
):
    if (start is not None and end is None) or (start is None and end is not None):
        raise ValueError('You must provide both start and end date')
    params:dict = {'key': self.key}
    if start is not None and end is not None:
        params['start'] = self._format_monitoring_dt(start)
        params['end'] = self._format_monitoring_dt(end)
    elif period is not None:
        params['period'] = period
    if proxy_pool is not None:
        params['proxy_pool'] = proxy_pool
    return (yield from self._monitoring_steps('/browser/monitoring/metrics', params))
def get_browser_monitoring_timeseries(self,
period: str | None = None,
proxy_pool: str | None = None,
start: datetime.datetime | None = None,
end: datetime.datetime | None = None)
Expand source code
@operation
def get_browser_monitoring_timeseries(
    self,
    period:Optional[str]=None,
    proxy_pool:Optional[str]=None,
    start:Optional[datetime.datetime]=None,
    end:Optional[datetime.datetime]=None,
):
    if (start is not None and end is None) or (start is None and end is not None):
        raise ValueError('You must provide both start and end date')
    params:dict = {'key': self.key}
    if start is not None and end is not None:
        params['start'] = self._format_monitoring_dt(start)
        params['end'] = self._format_monitoring_dt(end)
    elif period is not None:
        params['period'] = period
    if proxy_pool is not None:
        params['proxy_pool'] = proxy_pool
    return (yield from self._monitoring_steps('/browser/monitoring/metrics/timeseries', params))
def get_crawler_monitoring_metrics(self,
format: str = 'structured',
period: str | None = None,
aggregation: List[Literal['account', 'project', 'target']] | None = None,
include_webhook: bool = False)
Expand source code
@operation
def get_crawler_monitoring_metrics(
    self,
    format:str=ScraperAPI.MONITORING_DATA_FORMAT_STRUCTURED,
    period:Optional[str]=None,
    aggregation:Optional[List[MonitoringAggregation]]=None,
    include_webhook:bool=False,
):
    return (yield from self._monitoring_steps(
        '/crawl/monitoring/metrics',
        self._build_metrics_params(format, period, aggregation, include_webhook),
    ))
def get_crawler_monitoring_target_metrics(self,
domain: str,
group_subdomain: bool = False,
period: Literal['subscription', 'last7d', 'last24h', 'last1h', 'last5m'] | None = 'last24h',
start: datetime.datetime | None = None,
end: datetime.datetime | None = None,
include_webhook: bool = False)
Expand source code
@operation
def get_crawler_monitoring_target_metrics(
    self,
    domain:str,
    group_subdomain:bool=False,
    period:Optional[MonitoringTargetPeriod]=ScraperAPI.MONITORING_PERIOD_LAST_24H,
    start:Optional[datetime.datetime]=None,
    end:Optional[datetime.datetime]=None,
    include_webhook:bool=False,
):
    return (yield from self._monitoring_steps(
        '/crawl/monitoring/metrics/target',
        self._build_target_params(domain, group_subdomain, period, start, end, include_webhook),
    ))
def get_extraction_monitoring_metrics(self,
format: str = 'structured',
period: str | None = None,
aggregation: List[Literal['account', 'project', 'target']] | None = None,
include_webhook: bool = False)
Expand source code
@operation
def get_extraction_monitoring_metrics(
    self,
    format:str=ScraperAPI.MONITORING_DATA_FORMAT_STRUCTURED,
    period:Optional[str]=None,
    aggregation:Optional[List[MonitoringAggregation]]=None,
    include_webhook:bool=False,
):
    return (yield from self._monitoring_steps(
        '/extraction/monitoring/metrics',
        self._build_metrics_params(format, period, aggregation, include_webhook),
    ))
def get_extraction_monitoring_target_metrics(self,
domain: str,
group_subdomain: bool = False,
period: Literal['subscription', 'last7d', 'last24h', 'last1h', 'last5m'] | None = 'last24h',
start: datetime.datetime | None = None,
end: datetime.datetime | None = None,
include_webhook: bool = False)
Expand source code
@operation
def get_extraction_monitoring_target_metrics(
    self,
    domain:str,
    group_subdomain:bool=False,
    period:Optional[MonitoringTargetPeriod]=ScraperAPI.MONITORING_PERIOD_LAST_24H,
    start:Optional[datetime.datetime]=None,
    end:Optional[datetime.datetime]=None,
    include_webhook:bool=False,
):
    return (yield from self._monitoring_steps(
        '/extraction/monitoring/metrics/target',
        self._build_target_params(domain, group_subdomain, period, start, end, include_webhook),
    ))
def get_monitoring_metrics(self,
format: str = 'structured',
period: str | None = None,
aggregation: List[Literal['account', 'project', 'target']] | None = None,
include_webhook: bool = False)
Expand source code
@operation
def get_monitoring_metrics(
    self,
    format:str=ScraperAPI.MONITORING_DATA_FORMAT_STRUCTURED,
    period:Optional[str]=None,
    aggregation:Optional[List[MonitoringAggregation]]=None,
    include_webhook:bool=False,
):
    return (yield from self._monitoring_steps(
        '/scrape/monitoring/metrics',
        self._build_metrics_params(format, period, aggregation, include_webhook),
    ))
def get_monitoring_target_metrics(self,
domain: str,
group_subdomain: bool = False,
period: Literal['subscription', 'last7d', 'last24h', 'last1h', 'last5m'] | None = 'last24h',
start: datetime.datetime | None = None,
end: datetime.datetime | None = None,
include_webhook: bool = False)
Expand source code
@operation
def get_monitoring_target_metrics(
    self,
    domain:str,
    group_subdomain:bool=False,
    period:Optional[MonitoringTargetPeriod]=ScraperAPI.MONITORING_PERIOD_LAST_24H,
    start:Optional[datetime.datetime]=None,
    end:Optional[datetime.datetime]=None,
    include_webhook:bool=False,
):
    return (yield from self._monitoring_steps(
        '/scrape/monitoring/metrics/target',
        self._build_target_params(domain, group_subdomain, period, start, end, include_webhook),
    ))
def get_screenshot_monitoring_metrics(self,
format: str = 'structured',
period: str | None = None,
aggregation: List[Literal['account', 'project', 'target']] | None = None,
include_webhook: bool = False)
Expand source code
@operation
def get_screenshot_monitoring_metrics(
    self,
    format:str=ScraperAPI.MONITORING_DATA_FORMAT_STRUCTURED,
    period:Optional[str]=None,
    aggregation:Optional[List[MonitoringAggregation]]=None,
    include_webhook:bool=False,
):
    return (yield from self._monitoring_steps(
        '/screenshot/monitoring/metrics',
        self._build_metrics_params(format, period, aggregation, include_webhook),
    ))
def get_screenshot_monitoring_target_metrics(self,
domain: str,
group_subdomain: bool = False,
period: Literal['subscription', 'last7d', 'last24h', 'last1h', 'last5m'] | None = 'last24h',
start: datetime.datetime | None = None,
end: datetime.datetime | None = None,
include_webhook: bool = False)
Expand source code
@operation
def get_screenshot_monitoring_target_metrics(
    self,
    domain:str,
    group_subdomain:bool=False,
    period:Optional[MonitoringTargetPeriod]=ScraperAPI.MONITORING_PERIOD_LAST_24H,
    start:Optional[datetime.datetime]=None,
    end:Optional[datetime.datetime]=None,
    include_webhook:bool=False,
):
    return (yield from self._monitoring_steps(
        '/screenshot/monitoring/metrics/target',
        self._build_target_params(domain, group_subdomain, period, start, end, include_webhook),
    ))
def list_crawler_schedules(self, *, status: str | None = None) ‑> Steps[typing.List[typing.Dict[str, typing.Any]]]
Expand source code
@operation
def list_crawler_schedules(self, *, status: Optional[str] = None) -> Steps[List[Schedule]]:
    params = {"status": status} if status else None
    return (yield from self._schedule_steps("GET", "/crawl/schedules", query=params))
def list_scrape_schedules(self, *, status: str | None = None) ‑> Steps[typing.List[typing.Dict[str, typing.Any]]]
Expand source code
@operation
def list_scrape_schedules(self, *, status: Optional[str] = None) -> Steps[List[Schedule]]:
    params = {"status": status} if status else None
    return (yield from self._schedule_steps("GET", "/scrape/schedules", query=params))
def list_screenshot_schedules(self, *, status: str | None = None) ‑> Steps[typing.List[typing.Dict[str, typing.Any]]]
Expand source code
@operation
def list_screenshot_schedules(self, *, status: Optional[str] = None) -> Steps[List[Schedule]]:
    params = {"status": status} if status else None
    return (yield from self._schedule_steps("GET", "/screenshot/schedules", query=params))
async def open(self)
Expand source code
async def open(self):
    if self._http is None:
        self._http = self._new_http()
def pause_schedule(self, schedule_id: str) ‑> Steps[typing.Dict[str, typing.Any]]
Expand source code
@operation
def pause_schedule(self, schedule_id: str) -> Steps[Schedule]:
    return (yield from self._schedule_steps("POST", "/schedules/" + quote(schedule_id, safe="") + "/pause"))
def resilient_scrape(self,
scrape_config: ScrapeConfig,
retry_on_errors: Set[Exception] | None = None,
retry_on_status_code: List[int] | None = None,
tries: int = 5,
delay: int = 20) ‑> Steps[ScrapeApiResponse]
Expand source code
@operation
def resilient_scrape(
    self,
    scrape_config:ScrapeConfig,
    retry_on_errors:Optional[Set[Exception]]=None,
    retry_on_status_code:Optional[List[int]]=None,
    tries: int = 5,
    delay: int = 20,
) -> Steps[ScrapeApiResponse]:
    if retry_on_errors is None:
        retry_on_errors = {ScrapflyError}
    assert isinstance(retry_on_errors, set), 'retry_on_errors is not a set()'

    # Exponential backoff until `tries` attempts or `delay` seconds.
    deadline = time.monotonic() + delay

    for attempt in range(tries):
        try:
            try:
                return (yield from self._scrape(scrape_config))
            except (UpstreamHttpClientError, UpstreamHttpServerError) as e:
                if retry_on_status_code is not None and e.api_response and e.api_response.upstream_status_code not in retry_on_status_code:
                    return e.api_response

                raise
        except tuple(retry_on_errors):
            remaining = deadline - time.monotonic()

            if attempt + 1 == tries or remaining <= 0:
                raise

            yield Sleep(min(retry_delay(attempt), remaining))
def resume_schedule(self, schedule_id: str) ‑> Steps[typing.Dict[str, typing.Any]]
Expand source code
@operation
def resume_schedule(self, schedule_id: str) -> Steps[Schedule]:
    return (yield from self._schedule_steps("POST", "/schedules/" + quote(schedule_id, safe="") + "/resume"))

Inherited members