Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Page init callback #128

Merged
merged 7 commits into from
Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
playwright_init_page meta key (docs)
  • Loading branch information
elacuesta committed Oct 2, 2022
commit 726b68f42a6bfa117e8c235998a8738952d4e9ff
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,31 @@ TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
For more information and important notes see
[Receiving Page objects in callbacks](#receiving-page-objects-in-callbacks).

* `playwright_init_page` (type `Optional[Union[Callable, str]]`, default `None`)

A coroutine function (`async def`) to be invoked immediately after creating
a page for the request. It receives the page as its only positional
argument. Useful for initialization code. Invoked only for newly created
pages, ignored if the page for the request already exists (e.g. by passing
`playwright_page`).

```python
async def init_page(page):
await page.add_init_script(path="./custom_init_script.js")

class AwesomeSpider(scrapy.Spider):
def start_requests(self):
yield scrapy.Request(
url="https://httpbin.org/headers",
meta={"playwright": True, "playwright_init_page": init_page},
)
```

**Important!**

`scrapy-playwright` uses `Page.route` & `Page.unroute` internally, please
avoid using these methods unless you know exactly what you're doing.

* `playwright_page_methods` (type `Iterable`, default `()`)

An iterable of `scrapy_playwright.page.PageMethod` objects to indicate
Expand Down
1 change: 1 addition & 0 deletions scrapy_playwright/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ async def _create_page(self, request: Request) -> Page:
if self.default_navigation_timeout is not None:
page.set_default_navigation_timeout(self.default_navigation_timeout)
init_page_function = request.meta.get("playwright_init_page")
init_page_function = load_object(init_page_function)
if init_page_function:
try:
await init_page_function(page)
Expand Down