使用Puppeteer检索JavaScript呈现的HTML

Sir*_*org 9 javascript node.js web-scraping google-chrome-headless puppeteer

我试图从这个NCBI.gov页面中删除 html .我需要包含#see-all URL片段,这样我才能保证获得搜索页,而不是从错误的基因页面https://www.ncbi.nlm.nih.gov/gene/119016中检索HTML .

URL片段不会传递到服务器,而是由页面客户端的javascript使用(在本例中)创建完全不同的HTML,这是您在浏览器中转到页面时获得的"查看"页面源",这是我想要检索的HTML.R readLines()忽略后跟#的url标记

我第一次尝试使用phantomJS,但它只是回到这里描述的错误的ReferenceError:找不到变量:地图,似乎从phantomJS不支持该NCBI使用某些功能,从而消除了解决这一路线造成的.

我使用以下使用node.js评估的Javascript在Puppeteer上取得了更多成功:

const puppeteer = require('puppeteer');
(async() => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto(
    'https://www.ncbi.nlm.nih.gov/gene/?term=AGAP8#see-all');
  var HTML = await page.content()
  const fs = require('fs');
  var ws = fs.createWriteStream(
    'TempInterfaceWithChrome.js'
  );
  ws.write(HTML);
  ws.end();
  var ws2 = fs.createWriteStream(
    'finishedFlag'
  );
  ws2.end();
  browser.close();
})();
Run Code Online (Sandbox Code Playgroud)

然而,这返回了似乎是预渲染的html.我如何(以编程方式)获取我在浏览器中获得的最终html?

小智 8

也许尝试等待

await page.waitForNavigation(5);
Run Code Online (Sandbox Code Playgroud)

之后

let html = await page.content();
Run Code Online (Sandbox Code Playgroud)


Car*_*elu 8

你可以尝试改变这个:

await page.goto(
  'https://www.ncbi.nlm.nih.gov/gene/?term=AGAP8#see-all');
Run Code Online (Sandbox Code Playgroud)

进入这个:

  await page.goto(
    'https://www.ncbi.nlm.nih.gov/gene/?term=AGAP8#see-all', {waitUntil: 'networkidle'});
Run Code Online (Sandbox Code Playgroud)

或者,您可以创建一个函数listenFor()来在页面加载时监听自定义事件:

function listenFor(type) {
  return page.evaluateOnNewDocument(type => {
    document.addEventListener(type, e => {
      window.onCustomEvent({type, detail: e.detail});
    });
  }, type);
}`

await listenFor('custom-event-ready'); // Listen for "custom-event-ready" custom event on page load.
Run Code Online (Sandbox Code Playgroud)

LE:

这也可能派上用场:

await page.waitForSelector('h3'); // replace h3 with your selector
Run Code Online (Sandbox Code Playgroud)