我怎样才能优化我的代码,它可以 运行 有效?
How can I optimize my code so, it can run effectively?
我正在尝试优化我的代码,让它运行得更快。这是代码的一部分,但它基本上所做的是从网站获取大量数据,找到特定值,然后将其打印在 console.log.
我的目标是优化我的代码,使我的代码和处理时间更短
const result = await page.evaluate(() => {
const tds = Array.from(document.querySelectorAll('.table-dark-row td b'))
return tds.map(td => td.innerText)
}); //fetches the data from an element from a website
so = 'Shares outstanding:' + result[4];
sf = 'Shares Float:' + result[10];
shof = 'Short Float:' + result[16];
sr = 'Short Ratio:' + result[24];
console.log(so, sf, shof, sr); //await browser.close();
});
当您引用一个 result[i]
时,您实际上不会多次获取页面,所以不用担心多次包含它。
你可以重构 page.evaluate
to page.$$eval
这样它会写得更简洁。 注意:您不会真正注意到两者之间的性能差异,它只会看起来更干净。 $$eval
在后台运行相同的 JavaScript 方法:
[...] runs Array.from(document.querySelectorAll(selector))
within the page and passes it as the first argument to pageFunction.
所以你可以这样使用它:
const results = await page.$$eval('.table-dark-row td b', tds => tds.map(td => td.innerText))
如果您遇到性能不佳,应该是脚本的另一部分。
我正在尝试优化我的代码,让它运行得更快。这是代码的一部分,但它基本上所做的是从网站获取大量数据,找到特定值,然后将其打印在 console.log.
我的目标是优化我的代码,使我的代码和处理时间更短
const result = await page.evaluate(() => {
const tds = Array.from(document.querySelectorAll('.table-dark-row td b'))
return tds.map(td => td.innerText)
}); //fetches the data from an element from a website
so = 'Shares outstanding:' + result[4];
sf = 'Shares Float:' + result[10];
shof = 'Short Float:' + result[16];
sr = 'Short Ratio:' + result[24];
console.log(so, sf, shof, sr); //await browser.close();
});
当您引用一个 result[i]
时,您实际上不会多次获取页面,所以不用担心多次包含它。
你可以重构 page.evaluate
to page.$$eval
这样它会写得更简洁。 注意:您不会真正注意到两者之间的性能差异,它只会看起来更干净。 $$eval
在后台运行相同的 JavaScript 方法:
[...] runs
Array.from(document.querySelectorAll(selector))
within the page and passes it as the first argument to pageFunction.
所以你可以这样使用它:
const results = await page.$$eval('.table-dark-row td b', tds => tds.map(td => td.innerText))
如果您遇到性能不佳,应该是脚本的另一部分。