首页 > 解决方案 > document.getElementById() 不适用于 puppeteer 查找和 idSVG上的元素

问题描述

Puppeteer 无法选择我使用 d3.js 创建的 svg 元素

这是异步函数内部的一个片段:

  const chromiumBrowser = await puppeteer.launch(BROWSER_CONFIG);
  const page = await chromiumBrowser.newPage();
  await page.goto(WIND_DISPLAY_CLIENT_URL);

  const result = await page.evaluate(x => {
    return Promise.resolve(document.getElementById('needle'));
  }, 7);
  const result2 = await page.evaluate(x => {
    return Promise.resolve(document.getElementById('needle'));
  }, 7);
  console.log('what is the result?');
  console.log(result);
  console.log(result2);
  console.log(result === result2);

  await delay(20000);

  const result3 = await page.evaluate(x => {
    return Promise.resolve(document.getElementById('needle'));
  }, 7);

  console.log('result 3 is after the timeout?');
  console.log(result3);

  await chromiumBrowser.close();

这是 SVG 在 DOM 中呈现的方式:

<path d="M5,0C3.333333333333333,-67.5,1.6666666666666667,-135,0,-135C- 
1.6666666666666667,-135,-3.333333333333333,0,-5,0C-3.333333333333333,0,-1.6666666666666667,5,0,5C1.6666666666666667,5,3.333333333333333,2.5,5,0" 
id="needle" transform="rotate(-180)"></path>

这是呈现它的 d3 代码片段:

this.updatedParentSvg = parentSvg
  .append('g')
  .data([lineData])
  .attr('class', 'pointer')
  .attr('id', 'pointer')
  .attr('transform', center);

const pointerLine = d3.line().curve(d3.curveMonotoneX);
this.needle = this.updatedParentSvg
  .append('path')
  .attr('d', pointerLine)
  .attr('id', 'needle')
  .attr('transform', 'rotate(' + this.config.minAngle + ')');

如果我选择父 DOM g 元素,我可以运行 document.getElementById 并取回值,但不能在路径元素上获取值,这就是问题所在。

标签: javascripthtmld3.jssvgpuppeteer

解决方案


如果您想使用 puppeteer 通过 ID 定位元素,可以使用 CSS 选择器方法waitForSelector(...)并输入字符串"*[id='some_id']"。当通过 ID 定位元素时,许多框架在后台使用 CSS 选择器。希望这可以帮助!


推荐阅读