gpt4 book ai didi

javascript - Puppeteer 无法可视化完整的 SVG 图表

转载 作者:太空宇宙 更新时间:2023-11-04 03:01:20 28 4
gpt4 key购买 nike

我在 Try Puppeteer 中使用此代码:

const browser = await puppeteer.launch();

const page = await browser.newPage();
await page.goto('https://www.barchart.com/futures/quotes/ESM19/interactive-chart/fullscreen');

const linkHandlers = await page.$x("//li[contains(text(), '1D')]");

if (linkHandlers.length > 0) {
await linkHandlers[0].click();
} else {
throw new Error("Link not found");
}

await page.$eval('input[name="fieldInput"]', el => el.value = '1');

console.log(await page.content())
// const text = page.evaluate(() => document.querySelector('rect'))
// text.then((r) => {console.log(r[0])})

await page.screenshot({path: 'screenshot.png'});

await browser.close();

Chrome 浏览器中加载的同一页面显示指示价格变动的条形图,但在 Puppeteer 中获得的屏幕截图中,图表是空的。

此外,page.content() 给出的 html 与我在 Chrome 中检查元素时看到的完全不同。

最佳答案

问题

当输入更改时,您不会等待请求得到解决。由于更改将触发请求,因此您应该使用 page.waitForResponse等待数据加载。

此外,这是一个 Angular 应用程序,如果您只是通过 el.value = '1' 更改字段的值,它似乎不喜欢它。相反,您需要尝试表现得更像人类(然后按退格键并键入输入值)。

解决方案

首先,您从文档中获取元素句柄 (input[name="fieldInput")。然后,聚焦该元素,按退格键删除其中的值。之后,您键入所需的输入值。

输入字段现在具有正确的值,现在我们需要通过在元素上调用 blur() 来触发 blur 事件。同时,我们等待对服务器的请求完成。请求完成后,我们应该给页面几毫秒的时间来渲染数据。

总而言之,生成的代码如下所示:

const browser = await puppeteer.launch();

const page = await browser.newPage();
await page.goto('https://www.barchart.com/futures/quotes/ESM19/interactive-chart/fullscreen');

// wait until the element appears
const linkHandler = await page.waitForXPath("//li[contains(text(), '1D')]");
await linkHandler.click();

// get the input field, focus it, remove what's inside, then type the value
const elementHandle = await page.$('input[name="fieldInput"]');
await elementHandle.focus();
await elementHandle.press('Backspace');
await elementHandle.type('1');

// trigger the blur event and wait for the response from the server
await Promise.all([
page.waitForResponse(response => response.url().includes('https://www.barchart.com/proxies/timeseries/queryminutes.ashx')),
page.evaluate(el => el.blur(), elementHandle)
]);

// give the page a few milliseconds to render the diagram
await page.waitFor(100);

await page.screenshot({path: 'screenshot.png'});
await browser.close();
<小时/>

代码改进

我还删除了 page.$x函数并将其替换为 page.waitForXPath功能。这可确保您的脚本等待页面加载,并且您要单击的元素可用,然后脚本才会继续。

关于javascript - Puppeteer 无法可视化完整的 SVG 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55560220/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com