javascript - 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 并取回值,但不能在路径元素上获取值,这就是问题所在。
解决方案
如果您想使用 puppeteer 通过 ID 定位元素,可以使用 CSS 选择器方法waitForSelector(...)
并输入字符串"*[id='some_id']"
。当通过 ID 定位元素时,许多框架在后台使用 CSS 选择器。希望这可以帮助!
推荐阅读
- model - 哪个型号更好?BIC值如何解释
- mysql - 将 tableA 中的选择查询结果添加为 tableB 中的新列
- node.js - 带有猫鼬的nodejs - 使用多个对象列表更新对象数组
- python - 如何从现有模型中图层的入站节点中删除 training=True?
- python - 如何使用相对导入启动 vscode 调试器?(Python)
- java - 按值分组地图列表并通过排序合并为分组列表
- java - @Value 属性在 spring 组件中返回 null
- function - 将打印文本的函数作为参数传递,在 Haskell 中的新状态后执行它
- symfony5 - KnpLabs/KnpSnappyBundle:HostNotFoundError (Symfony 5)
- google-apps-script - 如何访问我的谷歌应用脚本网络应用?