如何添加剧作家的等待时间

How to add a waiting time with playwright

我正在将 scrapy 与 playwright 集成,但发现自己在点击后添加计时器时遇到了困难。因此,当我在点击后对页面进行截图时,它仍然挂在登录页面上。

如何集成一个计时器,让页面等待几秒钟直到页面加载?

import scrapy
from scrapy_playwright.page import PageCoroutine

class DoorSpider(scrapy.Spider):
    name = 'door'
    start_urls = ['https://nextdoor.co.uk/login/']

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(
                url=url, 
                callback = self.parse, 
                meta= dict(
                        playwright = True,
                        playwright_include_page = True,
                        playwright_page_coroutines = [
                        PageCoroutine("click", selector = ".onetrust-close-btn-handler.onetrust-close-btn-ui.banner-close-button.onetrust-lg.ot-close-icon"),
                        PageCoroutine("fill", "#id_email", 'my_email'),
                        PageCoroutine("fill", "#id_password", 'my_password'),
                        PageCoroutine('waitForNavigation'),
                        PageCoroutine("click", selector="#signin_button"),
                        PageCoroutine("screenshot", path="cookies.png", full_page=True),
                        
                                ]
                            )
            )

    def parse(self, response):
        yield {
            'data':response.body
        }

根据您的特定用例,您可以使用许多 waiting 方法。以下是示例,但您可以从 docs

阅读更多内容
  1. wait_for_event(event, **kwargs)
  2. wait_for_selector(selector, **kwargs)
  3. wait_for_load_state(**kwargs)
  4. wait_for_url(url, **kwargs)
  5. wait_for_timeout(timeout

对于你的问题,如果你需要等到页面加载,你可以使用下面的协程并将其插入到列表中的适当位置:

...
PageCoroutine("wait_for_load_state", "load"),
...

...
PageCoroutine("wait_for_load_state", "domcontentloaded"),
...

如果以上两种方法不起作用,您可以尝试其他任何一种 wait 方法,或者您可以使用明确的超时值,例如 3 秒。(不推荐这样做,因为它会更频繁地失败并且在网络抓取时不是最佳的)

...
PageCoroutine("wait_for_timeout", 3000),
...