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

How do I set custom locations based on latitude and longitude in Node.js?

我需要能够在进行 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());
})();

您可以创建 CDPSession and override the geolocation using the Chrome DevTools Protocol Page.setGeolocationOverride:

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

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

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});