如何使用puppeteer

时间:2018-04-04 06:17:48

标签: javascript node.js git automation puppeteer

> const puppeteer = require('puppeteer');
> 
> (async () => {
>     const browser = await puppeteer.launch();
>     const page = await browser.newPage();
>     await page.goto('https://en.wikipedia.org', {waitUntil: 'networkidle2'});
> 
>     await page.waitFor('input[name=search]');
> 
>     // await page.type('input[name=search]', 'Adenosine triphosphate');
>     await page.$eval('input[name=search]', el => el.value = 'Adenosine triphosphate');
> 
>     await page.click('input[type="submit"]');
>     await page.waitForSelector('#mw-content-text');
>     const text = await page.evaluate(() => {
>         const anchor = document.querySelector('#mw-content-text');
>         return anchor.textContent;
>     });
>     console.log(text);
>     await browser.close(); })();

这是使用puppeteer(https://github.com/GoogleChrome/puppeteer

填写表单的标准示例

现在我的问题是我是否有像test.json这样的外部json文件

  

{“搜索”:“硫化氢”}

我想在我的json文件中使用

中的值
await page.$eval() 

功能而非硬编码

await page.$eval('input[name=search]', el => el.value = 'Adenosine triphosphate');

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

尝试使用此代码或其附近的代码:



var fs = require('fs');
var data = JSON.parse(fs.readFileSync('filename.json', 'utf8'));

const fields = Object.entries(data);

const fillField = async (selector, value, page) => {
  const element = await page.$(selector);
  if (!element) throw new Error(`Could not find element with selector ${selector}`);
  await element.type(value);
};

for (let i=0; i < fields.length; i++) {
  const field = fields[i];
  const value = data[field];
  const selector = `input[name="${field}"`;
  await fillField(selector, value, page);
}
&#13;
&#13;
&#13;