我如何使用 Playwright 与 Google 地图或 OpenStreetMaps 等地图进行交互?

How do I interact with a map like Google Maps or OpenStreetMaps with Playwright?

我一直在尝试使用 Playwright 与 Google 地图或 OpenStreetMaps 等网站的地图组件进行交互。我试过将 browser.mouse.move()、browser.mouse.up() 和 browser.mouse.down() 的组合与文字作为参数。当我 运行 它时,它似乎根本没有对地图做任何事情。

有没有办法用 Playwright 移动地图?

我创建了一个 GitHub 存储库,以便可以轻松复制它。我还将在下面提供代码。 https://github.com/vincent-woodward/Playwright-Map-Interaction

const { chromium } = require("playwright");

(async () => {
  const browser = await chromium.launch({ headless: false });
  const page = await browser.newPage();

  //await page.goto("https://www.google.com/maps");
  await page.goto("https://www.openstreetmap.org/#map=4/38.01/-95.84");

  await page.mouse.move(600, 300);
  await page.mouse.down();
  await page.mouse.move(1200, 450);
  await page.mouse.up();

  browser.close();
})();

好消息!看起来这是 freshly added about a day ago!

View source/test implementation

查看 PR 后,您的代码应该可以工作:

await page.mouse.move(600, 300);
await page.mouse.down();
await page.mouse.move(1200, 450); // NOTE: make sure your viewport is big enough for this
await page.mouse.up();

这对我来说适用于笔记本电脑。您还可以删除 delay

的循环
const { chromium } = require("playwright");
(async () => {
  const browser = await chromium.launch({ headless: false });
  const page = await browser.newPage();
 //await page.goto("https://www.google.com/maps");
  await page.goto("https://www.openstreetmap.org/#map=4/38.01/-95.84");

  await page.click('#map',{force:true});//here the trick
  await page.mouse.down();

  await page.mouse.move(890, 80);
  for(var i = 0;i<1000000000;i++){}
  await page.mouse.move(400, 180); 
  for(var i = 0;i<1000000000;i++){}
  await page.mouse.move(700, 300); 

  await page.mouse.up();
//browser.close();
})();

我发现,如果您将 {steps: 5} 添加到移动命令中,它将按预期工作。我想到了关于 openstreet 地图和传单的移动地图界面,希望有一系列的鼠标移动事件。

const { chromium } = require("playwright");

(async () => {
   const browser = await chromium.launch({ headless: false });
   const page = await browser.newPage();

   //await page.goto("https://www.google.com/maps");
   await page.goto("https://www.openstreetmap.org/#map=4/38.01/-95.84");

   await page.mouse.move(600, 300);
   await page.mouse.down();
   await page.mouse.move(1200, 450, {steps: 5});  // <-- Change here
   await page.mouse.up();

   browser.close();
})();