在Google Computing Platform上使用puppeteer抓取沃尔玛产品

时间:2020-04-16 04:14:45

标签: google-cloud-platform puppeteer

我尝试在Google Cloud Platform(VM实例)上使用puppeteer。 该代码在我的本地计算机上正常运行。但是,当我在GCP上运行它时,总是会收到请求的禁止响应。 我需要在GCP上进行任何配置吗?

example.js

const puppeteer = require('puppeteer');
(async () => {
        const browser = await puppeteer.launch({
        args: [
            '--no-sandbox',
        ],
    });
        const page = await browser.newPage();
        await page.goto('https://walmart.com');
        const bodyHTML = await page.evaluate(() => document.body.innerHTML);
        console.log(bodyHTML);
        await browser.close();
})();

package.json

{
  "name": "example",
  "version": "1.0.0",
  "description": "",
  "main": "example.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "puppeteer": "^3.0.0"
  }
}

运行example.js

node example.js 
Forbidden
1587058087-94-320-69028280

如果我更改为解析www.target.com,则可以正常运行。

1 个答案:

答案 0 :(得分:0)

我发现需要设置“ UserAgent”。例如,

page.setUserAgent(
                    'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0',
                );

然后它起作用。谢谢大家的帮助。