A library to use Puppeteer-managed browser in Scrapy spiders
Project description
Scrapy-puppeteer-client
This package aims to manage Chrome browser with Puppeteer from Scrapy spiders. This allows to scrape sites that require JS to function properly and to make the scraper more similar to humans. It is a client library for scrapy-puppeteer-service.
⚠️ This repository is under development.
This project is under development. Use it at your own risk.
Installation
Using pip (master branch):
$ pip install scrapy-puppeteer-client
Configuration
You should have scrapy-puppeteer-service started.
Then add its URL to settings.py
and enable puppeteer downloader middleware:
DOWNLOADER_MIDDLEWARES = {
'scrapypuppeteer.middleware.PuppeteerServiceDownloaderMiddleware': 1042
}
PUPPETEER_SERVICE_URL = 'http://localhost:3000'
#To run locally (without scrapy-puppeteer-service started), you need to enable the setting:
PUPPETEER_LOCAL = True
For local execution it is also necessary to install Chromium for Pyppeteer.
Configuration
You should have scrapy-puppeteer-service started.
Then add its URL to settings.py
and enable puppeteer downloader middleware:
DOWNLOADER_MIDDLEWARES = {
'scrapypuppeteer.middleware.PuppeteerServiceDownloaderMiddleware': 1042
}
PUPPETEER_SERVICE_URL = 'http://localhost:3000'
Basic usage
Use scrapypuppeteer.PuppeteerRequest
instead of scrapy.Request
to render URLs with Puppeteer:
import scrapy
from scrapypuppeteer import PuppeteerRequest
class MySpider(scrapy.Spider):
...
def start_requests(self):
yield PuppeteerRequest('https://exapmle.com', callback=self.parse)
def parse(self, response):
links = response.css(...)
...
Puppeter responses
There is a parent PuppeteerResponse
class from which other response classes are inherited.
Here is a list of them all:
PuppeteerHtmlResponse
- hashtml
andcookies
propertiesPuppeteerScreenshotResponse
- hasscreenshot
propertyPuppeteerHarResponse
- hashar
propertyPuppeteerJsonResponse
- hasdata
property andto_html()
method which tries to transform itself toPuppeteerHtmlResponse
PuppeteerRecaptchaSolverResponse(PuppeteerJsonResponse, PuppeteerHtmlResponse)
- hasrecaptcha_data
property
Advanced usage
PuppeteerRequest
's first argument is a browser action.
Available actions are defined in scrapypuppeteer.actions
module as subclasses of PuppeteerServiceAction
.
Passing a URL into request is a shortcut for GoTo(url)
action.
Here is the list of available actions:
GoTo(url, options)
- navigate to URLGoForward(options)
- navigate forward in historyGoBack(options)
- navigate back in historyClick(selector, click_options, wait_options)
- click on element on pageScroll(selector, wait_options)
- scroll pageScreenshot(options)
- take screenshotHar()
- to get the HAR file, pass thehar_recording=True
argument toPuppeteerRequest
at the start of execution.RecaptchaSolver(solve_recaptcha)
- find or solve recaptcha on pageCustomJsAction(js_function)
- evaluate JS function on page
Available options essentially mirror service method parameters, which in turn mirror puppeteer API functions to some extent.
See scrapypuppeteer.actions
module for details.
You may pass close_page=False
option to a request to retain browser tab and its state after request's completion.
Then use response.follow
to continue interacting with the same tab:
import scrapy
from scrapypuppeteer import PuppeteerRequest, PuppeteerHtmlResponse
from scrapypuppeteer.actions import Click
class MySpider(scrapy.Spider):
...
def start_requests(self):
yield PuppeteerRequest(
'https://exapmle.com', # will be transformed into GoTo action
close_page=False,
callback=self.parse,
)
def parse(self, response: PuppeteerHtmlResponse):
...
# parse and yield some items
...
next_page_selector = 'button.next-page-or-smth'
if response.css(next_page_selector ):
yield response.follow(
Click(
next_page_selector,
wait_options={'selectorOrTimeout': 3000}, # wait 3 seconds
),
close_page=False,
callback=self.parse,
)
On your first request service will create new incognito browser context and new page in it.
Their ids will be in returned in response object as context_id
and page_id
attributes.
Following such response means passing context and page ids to next request.
You also may specify requests context and page ids directly.
Right before your spider has done the crawling, the service middleware will take care
of closing all used browser contexts with scrapypuppeteer.CloseContextRequest
.
It accepts a list of all browser contexts to be closed.
One may customize which PuppeteerRequest
's headers will be sent to remote website by the service
via include_headers
attribute in request or globally with PUPPETEER_INCLUDE_HEADERS
setting.
Available values are True (all headers), False (no headers) or list of header names.
By default, only cookies are sent.
You would also like to send meta with your request. By default, you are not allowed to do this
in order to sustain backward compatibility. You can change this behaviour by setting PUPPETEER_INCLUDE_META
to True.
Automatic recaptcha solving
Enable PuppeteerRecaptchaDownloaderMiddleware to automatically solve recaptcha during scraping. We do not recommend to use RecaptchaSolver action when the middleware works.
DOWNLOADER_MIDDLEWARES = {
'scrapypuppeteer.middleware.PuppeteerRecaptchaDownloaderMiddleware': 1041,
'scrapypuppeteer.middleware.PuppeteerServiceDownloaderMiddleware': 1042
}
Note that the number of RecaptchaMiddleware has to be lower than ServiceMiddleware's. You must provide some settings to use the middleware:
PUPPETEER_INCLUDE_META = True # Essential to send meta
RECAPTCHA_ACTIVATION = True # Enables the middleware
RECAPTCHA_SOLVING = False # Automatic recaptcha solving
RECAPTCHA_SUBMIT_SELECTORS = { # Selectors for "submit recaptcha" button
'www.google.com/recaptcha/api2/demo': '', # No selectors needed
}
If you set RECAPTCHA_SOLVING to False the middleware will try to find captcha and will notify you about number of found captchas on the page.
If you don't want the middleware to work on specific request you may provide special meta key: 'dont_recaptcha': True
.
In this case RecaptchaMiddleware will just skip the request.
TODO
- skeleton that could handle goto, click, scroll, and actions
- headers and cookies management
- proxy support for puppeteer
- error handling for requests
- har support
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for scrapy_puppeteer_client-0.3.4.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | bf609db747337f5e75369b366b5c833564fc6a04d3487aeac743b5f365c993d4 |
|
MD5 | 65bf166c1147aaddc702de3437d69c1a |
|
BLAKE2b-256 | 17be3e4e9ad5eac1b3ec2000622532c4ee9329d0bb5519435510acaca1fef200 |
Hashes for scrapy_puppeteer_client-0.3.4-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 03ec1a2d430ac066fd628376e43bb36b5b3b390f61819f866d1f2cab546d6d08 |
|
MD5 | e656409628b6f7e30737030edb19e520 |
|
BLAKE2b-256 | 8200ee548dd429ee863b38df8f4451f9614174a09d1e706bbae9aa44e4830c34 |