Ejemplo n.º 1
0
 async def new_cdp_session(self, page: Union[Page, Frame]) -> CDPSession:
     page = to_impl(page)
     params = {}
     if isinstance(page, Page):
         params["page"] = page._channel
     elif isinstance(page, Frame):
         params["frame"] = page._channel
     else:
         raise Error("page: expected Page or Frame")
     return from_channel(await self._channel.send("newCDPSession", params))
Ejemplo n.º 2
0
    async def fetch(
        self,
        urlOrRequest: Union[str, network.Request],
        params: Dict[str, Union[bool, float, str]] = None,
        method: str = None,
        headers: Headers = None,
        data: Union[Any, bytes, str] = None,
        form: Dict[str, Union[bool, float, str]] = None,
        multipart: Dict[str, Union[bytes, bool, float, str,
                                   FilePayload]] = None,
        timeout: float = None,
        failOnStatusCode: bool = None,
        ignoreHTTPSErrors: bool = None,
    ) -> "APIResponse":
        request = (cast(network.Request, to_impl(urlOrRequest)) if isinstance(
            to_impl(urlOrRequest), network.Request) else None)
        assert request or isinstance(
            urlOrRequest,
            str), "First argument must be either URL string or Request"
        assert (
            (1 if data else 0) + (1 if form else 0) + (1 if multipart else 0)
        ) <= 1, "Only one of 'data', 'form' or 'multipart' can be specified"
        url = request.url if request else urlOrRequest
        method = method or (request.method if request else "GET")
        # Cannot call allHeaders() here as the request may be paused inside route handler.
        headers_obj = headers or (request.headers if request else None)
        serialized_headers = serialize_headers(
            headers_obj) if headers_obj else None
        json_data: Any = None
        form_data: Optional[List[NameValue]] = None
        multipart_data: Optional[List[FormField]] = None
        post_data_buffer: Optional[bytes] = None
        if data:
            if isinstance(data, str):
                if is_json_content_type(serialized_headers):
                    json_data = data
                else:
                    post_data_buffer = data.encode()
            elif isinstance(data, bytes):
                post_data_buffer = data
            elif isinstance(data, (dict, list, int, bool)):
                json_data = data
            else:
                raise Error(f"Unsupported 'data' type: {type(data)}")
        elif form:
            form_data = object_to_array(form)
        elif multipart:
            multipart_data = []
            # Convert file-like values to ServerFilePayload structs.
            for name, value in multipart.items():
                if is_file_payload(value):
                    payload = cast(FilePayload, value)
                    assert isinstance(
                        payload["buffer"],
                        bytes), f"Unexpected buffer type of 'data.{name}'"
                    multipart_data.append(
                        FormField(name=name,
                                  file=file_payload_to_json(payload)))
                elif isinstance(value, str):
                    multipart_data.append(FormField(name=name, value=value))
        if (post_data_buffer is None and json_data is None
                and form_data is None and multipart_data is None):
            post_data_buffer = request.post_data_buffer if request else None
        post_data = (base64.b64encode(post_data_buffer).decode()
                     if post_data_buffer else None)

        def filter_none(input: Dict) -> Dict:
            return {k: v for k, v in input.items() if v is not None}

        response = await self._channel.send(
            "fetch",
            filter_none({
                "url": url,
                "params": object_to_array(params),
                "method": method,
                "headers": serialized_headers,
                "postData": post_data,
                "jsonData": json_data,
                "formData": form_data,
                "multipartData": multipart_data,
                "timeout": timeout,
                "failOnStatusCode": failOnStatusCode,
                "ignoreHTTPSErrors": ignoreHTTPSErrors,
            }),
        )
        return APIResponse(self, response)