如何从阴影根元素获取文本? [英] How to get text from shadow root element?
问题描述
我有一个使用 Puppeteer 自动化的网页.我想从阴影根元素中获取文本.我的困惑是通过在浏览器设置中启用属性来启用阴影根元素可见性.但是当脚本运行一个新的浏览器实例时,默认情况下禁用 shadow root.那么我如何访问该元素.有没有办法以编程方式启用影子根.我附上了我的 DOM 元素的屏幕截图.
I have a web page that I am automating using Puppeteer. I want to get a text out of shadow root element. My confusion is that shadow root element visibility is enabled by enabling property in the browser setting. But when the script run a new browser instance is launched with shadow root disabled by default. So how can I access the element. Is there any way to enabled shadow root pro grammatically. I am attaching screenshot of my DOM element.
推荐答案
您可以使用 query-selector-shadow-dom 与 puppeteer 一起使用的 npm 包.
You can use query-selector-shadow-dom npm package for this purpose with puppeteer.
const puppeteer = require('puppeteer');
const { QueryHandler } = require('query-selector-shadow-dom/plugins/puppeteer');
(async () => {
try {
await puppeteer.__experimental_registerCustomQueryHandler('shadow', QueryHandler);
const browser = await puppeteer.launch({
headless: false
});
const page = await browser.newPage();
await page.goto('http://some-site.com/');
await page.waitForSelector('shadow/div'); // if it'd have a class you could replace "div" with the ".class-name"
const shadowDiv = await page.$('shadow/div');
const text = await page.evaluate(el => el.innerText, shadowDiv);
await browser.close();
} catch (e) {
console.error(e);
}
})()
您提到您需要在 chrome 设置中应用 shadow DOM,我建议使用所需设置创建一个 chrome 配置文件(Custom Profile 1
),然后将此配置文件与 puppeteer 一起使用:
You mentioned you need to apply shadow DOM in chrome settings, I suggest to create a chrome profile (Custom Profile 1
) with the required settings and then use this profile with puppeteer:
例如:
const browser = await puppeteer.launch({
headless: false,
args: [
'--user-data-dir=C:\\Users\\user.name\\AppData\\Local\\Chromium\\User Data',
'--profile-directory=Custom Profile 1'
]
})
以上示例适用于 Windows,查看更多平台和更多信息 这里.
The example above is for Windows, see more platforms and more info here.
这篇关于如何从阴影根元素获取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!