如何使用Scrapy Playwight设置页面视口大小?

2uluyalo  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(288)

我没有找到任何令人满意的答案。我想要的只是在请求模拟该尺寸的屏幕之前将视口设置为1080*19200(是的,1920 * 10)。
使用Scrapy Playwright可以做到这一点吗?如果是这样,我该怎么做?

k5ifujac

k5ifujac1#

有多种方法可以做到这一点:
1.在上下文中。Playwright的Browser.new_context方法接受一个viewport参数,可以在PLAYWRIGHT_CONTEXTS设置中使用:

# settings.py
PLAYWRIGHT_CONTEXTS = {
    "default": {
        "viewport": {
            "width": 19200,
            "height": 1080,
        },
    },
}

1.在页面中。您可以从页面初始化回调调用Page.set_viewport_size

async def init_page(page, request):
    await page.set_viewport_size({"width": 19200, "height": 1080})
yield scrapy.Request(
    url="https://example.org",
    meta={
        "playwright": True,
        "playwright_page_init_callback": init_page,
    },
)

1.在页面中,使用PageMethod

from scrapy_playwright.page import PageMethod
yield scrapy.Request(
    url="https://example.org",
    meta={
        "playwright": True,
        "playwright_page_methods": [
            PageMethod("set_viewport_size", {"width": 19200, "height": 1080}),
        ],
    },
)

相关问题