如何根据Node.js中的纬度和经度设置自定义位置?

时间:2017-10-27 06:25:18

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

我需要能够在进行无头Chrome(Puppeteer)搜索时根据纬度和经度设置位置:

const puppeteer = require('puppeteer');
var url="https://www.google.com/search?q=";
var keyword="hotels&num=100";
var urls;
var desktopUserAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";
const response=[];
var i=0;
var userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36";

(async () => 
  const browser = await puppeteer.launch({headless: false });
  const page = await browser.newPage();
  urls=url+keyword;
    /*page.setViewport({
        width: 1000,
        height: 1000
    });*/
page.setUserAgent(userAgent);
  response[i]=await page.goto(urls);
  console.log(await browser.version());
})();

2 个答案:

答案 0 :(得分:1)

您可以创建CDPSession并使用Chrome DevTools协议Page.setGeolocationOverride覆盖地理位置:

const client = await page.target().createCDPSession();

await client.send('Emulation.setGeolocationOverride', {
  accuracy: 100,
  latitude: 24.42312,
  longitude: 105.75868,
});

答案 1 :(得分:0)

page.setGeolocation api

文档:https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#pagesetgeolocationoptions

代码示例:

  const browser = await puppeteer.launch({headless: false}); // default is true
  const page = await browser.newPage();
  // 116.451673,39.923054
  await page.setGeolocation({latitude: 39.923054, longitude: 130.451673});