NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

Web scraping

How to use Scrapy with Playwright

scrapy-playwright lets a Scrapy project send chosen requests through a real browser while everything else stays plain HTTP. You keep the scheduler, pipelines and settings you know, and gain JavaScript rendering where it is needed.

What the plugin does

scrapy-playwright replaces Scrapy's download handler for HTTP and HTTPS with one that can route a request through Playwright. Requests marked with meta={"playwright": True} are opened in a browser page; the rendered HTML comes back as a normal Scrapy response, so your selectors and callbacks work unchanged. Requests without the flag are downloaded the usual way, without a browser. That makes it easy to render only the pages that need it.

Install and configure

pip install scrapy-playwright
playwright install chromium

The second command downloads the browser build Playwright drives. Then add the handlers and the asyncio reactor to settings.py:

DOWNLOAD_HANDLERS = {
    "http": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
    "https": "scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler",
}
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
PLAYWRIGHT_BROWSER_TYPE = "chromium"
PLAYWRIGHT_LAUNCH_OPTIONS = {"headless": True}
PLAYWRIGHT_DEFAULT_NAVIGATION_TIMEOUT = 30_000
PLAYWRIGHT_MAX_PAGES_PER_CONTEXT = 4

Setting names here match the plugin's documentation at the time of writing; check its README for your installed version, since options are added from release to release. PLAYWRIGHT_MAX_PAGES_PER_CONTEXT caps how many tabs one context keeps open, which is the main lever for memory use.

A first rendered request

Mark the request and wait for the content you need before the HTML is captured. PageMethod lets you call any Playwright page method, in order, before the response is returned.

import scrapy
from scrapy_playwright.page import PageMethod

class EventsSpider(scrapy.Spider):
    name = "events"

    def start_requests(self):
        yield scrapy.Request(
            "https://events.example.org/upcoming",
            meta={"playwright": True, "playwright_page_methods": [
                PageMethod("wait_for_selector", "li.event-card"),
            ]},
        )

    def parse(self, rendered):
        for card in rendered.css("li.event-card"):
            yield {"name": card.css("h3::text").get(default="").strip(),
                   "date": card.css("time::attr(datetime)").get()}

Without the wait, the response could be captured before the script fills in the list and your selectors would find nothing. Always wait for a concrete element rather than a fixed sleep.

Scrolling and clicking with page methods

Pages that load more items as you scroll need a few actions before the capture. Page methods run in sequence, so you can script a short interaction:

scroll_twice = [
    PageMethod("wait_for_selector", "div.result"),
    PageMethod("evaluate", "window.scrollTo(0, document.body.scrollHeight)"),
    PageMethod("wait_for_timeout", 1200),
    PageMethod("evaluate", "window.scrollTo(0, document.body.scrollHeight)"),
    PageMethod("wait_for_load_state", "networkidle"),
]
yield scrapy.Request(url, meta={"playwright": True, "playwright_page_methods": scroll_twice})

For longer or conditional interactions, such as "click Load more until it disappears", use the page object directly instead.

Working with the page object

Set playwright_include_page and the live Playwright page arrives in response.meta["playwright_page"]. Your callback must be async, and you must close the page yourself, also when something fails, or tabs pile up until the context limit blocks new requests.

class LoadMoreSpider(scrapy.Spider):
    name = "catalog_pw"

    def start_requests(self):
        yield scrapy.Request("https://catalog.example.org/all",
                             meta={"playwright": True, "playwright_include_page": True},
                             errback=self.close_on_error)

    async def parse(self, response):
        page = response.meta["playwright_page"]
        try:
            more = page.locator("button.load-more")
            while await more.is_visible():
                await more.click()
                await page.wait_for_timeout(800)
            html = await page.content()
        finally:
            await page.close()
        for row in scrapy.Selector(text=html).css("div.sku"):
            yield {"sku": row.attrib.get("data-sku")}

    async def close_on_error(self, failure):
        page = failure.request.meta.get("playwright_page")
        if page:
            await page.close()

Note that after clicking, the original response no longer reflects the page, so the code reads page.content() and parses that with a fresh Selector.

Contexts for separate sessions

A browser context is an isolated profile with its own cookies and storage. Name a context in meta["playwright_context"] to keep sessions apart, for example one per account in a QA crawl, or one per proxy. Context options, such as a proxy or a locale, can be set per context in the PLAYWRIGHT_CONTEXTS setting or through playwright_context_kwargs in meta when the context is created. Requests that share a context name share its cookies, which is how a login or a cleared challenge carries over to later pages.

Block what you do not need

A browser downloads images, fonts and media you will never parse. The PLAYWRIGHT_ABORT_REQUEST setting takes a function that decides, per browser request, whether to abort it.

def skip_heavy(req):
    return req.resource_type in {"image", "media", "font"} or "analytics" in req.url

PLAYWRIGHT_ABORT_REQUEST = skip_heavy

This often cuts page load time and bandwidth noticeably. Be careful with stylesheets: some sites hide content until CSS loads, so block them only after testing.

Mixing rendered and plain requests

The plugin pays off most when you use the browser sparingly. A typical pattern is to fetch listing pages as plain HTTP (fast, many at once) and render only detail pages that build their content with JavaScript, or the reverse. Because the flag is per request, the split is just a matter of which requests carry "playwright": True. Our comparison of Scrapy and Selenium discusses when a page truly needs a browser.

CAPTCHAs on rendered pages

When a rendered page shows a token CAPTCHA such as reCAPTCHA or Turnstile, you can solve it through an API and place the token in the page from an async callback with page.evaluate, then submit. For firewall checks that end in a cookie, add the cookie to the context with page.context.add_cookies and reload. The Playwright integration shows both patterns, and the Scrapy middleware guide handles challenges for the plain HTTP requests in the same project.

Debugging a rendered request

When a rendered page does not contain what you expect, look at it the way the browser saw it. Temporarily set PLAYWRIGHT_LAUNCH_OPTIONS = {"headless": False} on your workstation and watch the page load, or add a PageMethod("screenshot", path="debug.png", full_page=True) to the request so a picture is saved next to the HTML. Comparing the screenshot with your selectors usually shows the problem within a minute: a cookie banner covering the list, a region prompt, a login wall or a challenge page. Remove the debug method again before a full crawl, since screenshots cost time on every page.

Troubleshooting

  • Reactor error at startup: the asyncio reactor is not set, or something imported Twisted's default reactor first. Set TWISTED_REACTOR in settings, not in code.
  • Empty selectors: the capture happened before rendering finished. Add a wait_for_selector page method.
  • Crawl stalls after a while: pages are not being closed. Close them in finally and in an errback.
  • High memory: lower PLAYWRIGHT_MAX_PAGES_PER_CONTEXT and CONCURRENT_REQUESTS, and block heavy resources.
Browsers put more load on a site than plain requests because they fetch every asset. Block what you do not need and keep concurrency low for rendered pages.

Common questions

Do all requests go through the browser after installing scrapy-playwright?

No. Only requests with playwright set to True in meta are rendered; the rest are downloaded as plain HTTP.

Why must I close the page when using playwright_include_page?

The plugin hands control of the page to you. Unclosed pages count against the per context limit and eventually block new requests.

Can I use Firefox instead of Chromium?

Yes. Set PLAYWRIGHT_BROWSER_TYPE to firefox and install it with playwright install firefox.

How do I wait for content before the response is captured?

Add a PageMethod such as wait_for_selector to playwright_page_methods, pointing at an element that only exists once the data is rendered.

Does scrapy-playwright need the asyncio reactor?

Yes. Set TWISTED_REACTOR to the asyncio selector reactor in settings.py.

Keep reading