【问题标题】:In puppeteer, how do you intercept a redirect after window.open?在 puppeteer 中,如何在 window.open 之后拦截重定向?
【发布时间】:2021-02-08 12:54:13
【问题描述】:

假设有一个网站,内容如下:

<script type="text/javascript">
  const onClick = async (event) => {
    var page = window.open('', '_blank');
    var url = await someCrypticFunctionality();
    page.location.replace(url);
  }
</script>
<button type="button" onclick="onClick">Click here</button>

使用 puppeteer 我想访问该页面,单击按钮(到目前为止一切顺利),然后检索 url,最好在请求位于该 URL 的任何内容之前。我该怎么做?

【问题讨论】:

    标签: javascript node.js asynchronous web-scraping puppeteer


    【解决方案1】:

    我认为this.request.isNavigationRequest 更适合您的情况。但您可能希望结合使用.redirectChain().legnthisNavigationRequest,因为您不想阻止第一次导航到页面本身

    await page.setRequestInterception(true);
    
    page.on("request", async request => {
      if (request.isNavigationRequest() && request.redirectChain().length > 0) {
        await request.abort();
      }
    });
    

    【讨论】:

    • 再次编辑。我认为 this.request.isNavigationRequest 更适合你的情况
    • 它的作品。老实说,我不确定您为什么要围绕它创建整个课程,但它确实有效,这才是最重要的:)
    • 这是我的风格。我假设你有更多的东西要添加到你的请求拦截器中。我将所有发生在请求对象上的类似操作分组在一个类中,请求者作为构造函数中的依赖项。如果你只写独立函数,请忽略
    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 2015-08-22
    • 2022-01-09
    • 1970-01-01
    • 2018-04-14
    • 2021-03-22
    • 2017-08-27
    相关资源
    最近更新 更多