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

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

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设置中使用:
  1. # settings.py
  2. PLAYWRIGHT_CONTEXTS = {
  3. "default": {
  4. "viewport": {
  5. "width": 19200,
  6. "height": 1080,
  7. },
  8. },
  9. }
  1. 在页面中。你可以在页面初始化回调函数中调用Page.set_viewport_size
  1. async def init_page(page, request):
  2. await page.set_viewport_size({"width": 19200, "height": 1080})
  1. yield scrapy.Request(
  2. url="https://example.org",
  3. meta={
  4. "playwright": True,
  5. "playwright_page_init_callback": init_page,
  6. },
  7. )
  1. 在页面中,使用PageMethod
  1. from scrapy_playwright.page import PageMethod
  1. yield scrapy.Request(
  2. url="https://example.org",
  3. meta={
  4. "playwright": True,
  5. "playwright_page_methods": [
  6. PageMethod("set_viewport_size", {"width": 19200, "height": 1080}),
  7. ],
  8. },
  9. )
英文:

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:
  1. # settings.py
  2. PLAYWRIGHT_CONTEXTS = {
  3. "default": {
  4. "viewport": {
  5. "width": 19200,
  6. "height": 1080,
  7. },
  8. },
  9. }
  1. In the page. You can call Page.set_viewport_size from a page init callback:
  1. async def init_page(page, request):
  2. await page.set_viewport_size({"width": 19200, "height": 1080})
  1. yield scrapy.Request(
  2. url="https://example.org",
  3. meta={
  4. "playwright": True,
  5. "playwright_page_init_callback": init_page,
  6. },
  7. )
  1. In the page, with a PageMethod:
  1. from scrapy_playwright.page import PageMethod
  1. yield scrapy.Request(
  2. url="https://example.org",
  3. meta={
  4. "playwright": True,
  5. "playwright_page_methods": [
  6. PageMethod("set_viewport_size", {"width": 19200, "height": 1080}),
  7. ],
  8. },
  9. )

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:

确定