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

huangapple go评论141阅读模式
英文:

How do I set the page viewport size using Scrapy Playwight?

问题

我没有找到关于这个问题的满意答案。我只想在请求之前将视口设置为1080*19200(是的,1920 * 10),以模拟那个尺寸的屏幕。

使用Scrapy Playwright是否可能实现这一点?如果可以,我该如何做到?

英文:

I didn't find any satisfactory answer about this. All I want is just set the viewport to 1080*19200 (yes, 1920 * 10) before the request to simulate a screen of that size.

Is this even possible using Scrapy Playwright? If so, how do i do that?

答案1

得分: 1

有多种方法可以实现这个:

  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}),
        ],
    },
)
英文:

There are multiple ways of doing this:

  1. In the context. Playwright's Browser.new_context method takes a viewport argument, which can be used in the PLAYWRIGHT_CONTEXTS setting:
# settings.py
PLAYWRIGHT_CONTEXTS = {
    "default": {
        "viewport": {
            "width": 19200,
            "height": 1080,
        },
    },
}
  1. In the page. You can call Page.set_viewport_size from a page init callback:
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. In the page, with a 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}),
        ],
    },
)

huangapple
  • 本文由 发表于 2023年8月9日 04:19:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定