Scrapy-Playwright Proxy Rotation: Scraping JS-Rendered Sites at Scale
Scrapy-Playwright Proxy Rotation: Scraping JS-Rendered Sites at Scale
Introduction
Scraping JavaScript-rendered websites can be challenging, especially when you need to handle dynamic content and scale your scraping operations. Traditional web scraping tools like Scrapy often fall short because they rely on static HTML responses, whereas modern websites heavily depend on JavaScript for rendering content.
Enter Scrapy-Playwright: This powerful middleware allows Scrapy to render JavaScript-heavy pages using Playwright, a headless browser automation library. Combining Scrapy's robust crawling framework with Playwright's ability to handle dynamic content makes it an excellent choice for scraping JS-rendered sites at scale.
In this guide, we'll walk you through setting up and optimizing your Scrapy project to use Scrapy-Playwright for proxy rotation. We'll cover everything from installing the necessary packages to configuring middleware settings and tuning performance parameters. By the end of this article, you'll have a solid understanding of how to scrape JS-rendered sites effectively using Scrapy-Playwright.
Setting Up Your Environment
Before we dive into the configuration details, let's set up your environment to use Scrapy-Playwright.
Install Required Packages
First, ensure you have Python and pip installed. Then, install Scrapy, Scrapy-Playwright, and any other necessary dependencies:
pip install scrapy scrapy-playwright playwright
After installing the packages, make sure to install Playwright's browser binaries by running:
playwright install
Initialize Your Scrapy Project
If you don't have a Scrapy project yet, initialize one with the following command:
scrapy startproject js_rendered_site_scraper
cd js_rendered_site_scraper
Configuring Scrapy-Playwright Middleware
Now that your environment is set up, let's configure Scrapy to use Scrapy-Playwright.
Enable Scrapy-Playwright Middleware
Edit your settings.py file in the Scrapy project directory and add the following configuration:
# settings.py
DOWNLOADER_MIDDLEWARES = {
'scrapy_playwright.middlewares.ScrapyPlaywrightDownloadHandler': 650,
}
PLAYWRIGHT_LAUNCH_OPTIONS = {
"headless": True,
# You can specify a proxy here if needed, but it's more flexible to use per-request
}
Configuring Proxy Rotation
To handle proxy rotation effectively, you can configure Scrapy-Playwright to use different proxies for each request. This is particularly useful when dealing with anti-scraping measures and IP bans.
#### Using Per-Request Proxies
You can specify a proxy directly in the playwright_page_goto method:
import scrapy
from scrapy_playwright.page import Page, Response
class JsRenderedSpider(scrapy.Spider):
name = "js_rendered_site"
start_urls = ["https://example.com"]
async def parse(self, response: Response, playwright_page: Page, **kwargs) -> dict:
await playwright_page.goto(
response.url,
proxy={
"server": "http://your-proxy-server:port",
"username": "your-username",
"password": "your-password"
}
)
# Extract data from the rendered page
yield {
'title': await playwright_page.title(),
'body': await playwright_page.content()
}
#### Combining with scrapy-rotating-proxies Middleware
For more advanced proxy management, you can combine Scrapy-Playwright with the scrapy-rotating-proxies middleware. First, install it:
pip install scrapy-rotating-proxies
Then, configure your settings.py:
# settings.py
DOWNLOADER_MIDDLEWARES = {
'scrapy_playwright.middlewares.ScrapyPlaywrightDownloadHandler': 650,
'scrapy_rotating_proxies.middlewares.RotatingProxyMiddleware': 610,
}
ROTATING_PROXY_LIST = [
"http://proxy1.com:port",
"http://proxy2.com:port",
# Add more proxies as needed
]
Performance Tuning
Scraping with Scrapy-Playwright can be resource-intensive, especially when dealing with a large number of concurrent requests. Here are some tips to optimize performance:
Limit Maximum Pages per Context
Setting PLAYWRIGHT_MAX_PAGES_PER_CONTEXT limits the number of pages that share the same browser context. This helps manage memory usage and reduce the risk of hitting rate limits.
# settings.py
PLAYWRIGHT_LAUNCH_OPTIONS = {
"headless": True,
}
PLAYWRIGHT_MAX_PAGES_PER_CONTEXT = 10 # Adjust based on your needs
Adjust Async Concurrency
Scrapy allows you to control the number of concurrent requests using the CONCURRENT_REQUESTS setting. For Scrapy-Playwright, you might want to limit this further due to the resource overhead.
# settings.py
CONCURRENT_REQUESTS = 16 # Adjust based on your system's capabilities
When to Use Scrapy-Playwright vs Standalone Playwright + Queue
Scrapy-Playwright is designed to work seamlessly with Scrapy, making it easier to integrate into existing Scrapy projects. However, if you prefer more control or need advanced features not provided by Scrapy-Playwright, using standalone Playwright with a custom queue might be the way to go.
Using Standalone Playwright
If you choose to use standalone Playwright, you'll have full control over the browser context and page management. This can be beneficial if you need to handle complex interactions or specific configurations not supported by Scrapy-Playwright.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://example.com")
# Perform actions and extract data
print(page.title())
browser.close()
Professional Proxy Services for Scrapy-Playwright
For production-scale scraping, using a reliable proxy service is crucial. Bright Data and SmartProxy are established providers that offer residential IPs, which can help bypass anti-scraping measures effectively.
Bright Data Example
If you decide to use Bright Data's residential proxy service with Scrapy-Playwright, configure your settings.py like this:
# settings.py
ROTATING_PROXY_LIST = [
"http://residential-proxy.brightdata.com:port",
]
Remember to replace "port" with the actual port number provided by Bright Data.
Conclusion
Scraping JavaScript-rendered sites at scale requires a powerful toolset that can handle dynamic content and manage proxies effectively. Scrapy-Playwright provides a robust solution for integrating Playwright's rendering capabilities into Scrapy, making it an excellent choice for developers looking to automate web scraping tasks.
By following the steps outlined in this guide, you should have a solid foundation for setting up and optimizing your Scrapy project with Scrapy-Playwright. Remember to always respect website terms of service and use proxies responsibly to avoid IP bans and legal issues.
If you'd rather not manage proxy lists manually, ProxyForge auto-tests and rotates proxies locally on your machine — one-off $29 unlock, no subscription: https://proxyforge.dev/#download
Free proxies break. ProxyForge doesn't.
The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.
Download ProxyForge free →