javascript - puppeteer 选择链接

标签 javascript node.js puppeteer google-chrome-headless

我想点击 html 页面中的链接,其中包含以下代码段:

<p>Die maximale Trefferanzahl von 200 wurde überschritten.
  <a href="/rp_web/search.do?doppelt">Verdoppeln Sie hier  Suchergebnislimit.</a>
</p>

我之前设置了一些过滤器,然后我加载了页面,它加载了我需要的页面。在生成的页面上,我想单击 html 片段中显示的链接。 我正在尝试使用的 js 是这个

await Promise.all([
    page.click('input#landNW'), // set a filter
    page.click('input[type=submit]'), // submit the form
    page.waitForNavigation(), // wait for the page to load
    page.click('p a'), // not working: double the search results
    page.waitForNavigation() // not working: waiting for the page to reload
]).catch(e => console.log(e)); // no error

我很确定 page.click('p a') 工作正常,因为在我的 chrome 浏览器的控制台中我可以执行 document.querySelector("p a") .click(),然后按预期重新加载页面。

我还尝试使用 href 属性来选择 url,例如使用 page.click('a[href="/rp_web/search.do?doppelt"]'),但出现错误: 没有找到选择器的 Node :a[href="/rp_web/search.do?doppelt"]

我怎样才能完成我期望发生的事情?

编辑 您可以在此处找到完整的存储库:bitbucket/ytNeskews

最佳答案

有很多关于 page.click 不起作用的报告,在您的情况下它确实由于某种原因不起作用。幸运的是,我们可以在旧的 page.evaluate(或 page.$eval)的帮助下完成所有事情:这里我在浏览器上下文中手动单击链接:

const puppeteer  = require ('puppeteer');
(async () => {
    const browser = await puppeteer.launch({ headless : false });
    const page = await browser.newPage();
    await page.goto('https://www.handelsregister.de/rp_web/mask.do?Typ=e');

    await Promise.all([
        page.click('input#landNW'), // set a filter
        page.click('input[type=submit]'), // submit the form
        page.waitForNavigation(), // wait for the page to load
    ]).catch(e => console.log(e));

    // Print the number of allowed results (must be 200)
    console.log(await page.$eval('#inhalt p', el => el.textContent.match(/\d+ hits/)[0]));

    await Promise.all([
         // Manual clicking of the link
         page.$eval('p a', el => el.click()),
         page.waitForNavigation()
    ]).catch(e => console.log(e));

    // Print the number of allowed results (must be 400 now)
    console.log(await page.$eval('#inhalt p', el => el.textContent.match(/\d+ hits/)[0]));

    await browser.close();
})();

结果:

200 hits
400 hits

也不是说您应该一次只等待一个页面导航。如果可以的话,再多说一句——用可见的 Chromium ({headless : false}) 编写这样的脚本要方便得多。

关于javascript - puppeteer 选择链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51011466/

相关文章:

node.js - 搜索时跳过奇数个前面的符号

node.js - headless false - 始终关注地址栏

javascript - babeljs 不能正确地转换扩展类

JavaScript 多边形碰撞检测

javascript - 如何使用 for in 循环遍历仅打印第二个属性的对象?

node.js - ENV 变量未正确添加到容器环境中

javascript - 获取关联数组的特定值及其键名

node.js - 为什么 Node 控制台不显示功能代码?

javascript - 使用 Puppeteer 将鼠标悬停在 Node.js 中的元素和 getComputedStyle 上?

javascript - 在 puppeteer js 中抓取网页时出错