简体   繁体   English

如何优化我的代码,使其可以有效运行?

[英]How can I optimize my code so, it can run effectively?

I'm trying to optimize my code so, it runs faster.我正在尝试优化我的代码,所以它运行得更快。 This is part of the code but what it basically does is takes a bunch of data from a website, finds the specific value and then prints it in the console.log.这是代码的一部分,但它的基本作用是从网站获取一堆数据,找到特定值,然后将其打印在 console.log 中。

My goal is to optimize my code so, that my code and process time are shorter我的目标是优化我的代码,使我的代码和处理时间更短

 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(); });

You actually don't fetch the page multiple times when you reference a result[i] , so no worries about include it multiple times.当您引用result[i]时,您实际上不会多次获取页面,因此不必担心多次包含它。

You could refactor the page.evaluate to page.$$eval so it will be written more concisely.您可以将page.evaluate重构为page.$$eval以便编写得更简洁。 Note: you won't really notice the performance difference between the two, it will only look cleaner.注意:你不会真正注意到两者之间的性能差异,它只会看起来更干净。 $$eval runs the same JavaScript methods under the hood: $$eval在后台运行相同的 JavaScript 方法:

[...] runs Array.from(document.querySelectorAll(selector)) within the page and passes it as the first argument to pageFunction. [...] 在页面内运行Array.from(document.querySelectorAll(selector))并将其作为第一个参数传递给 pageFunction。

So you could use it like this:所以你可以像这样使用它:

const results = await page.$$eval('.table-dark-row td b', tds => tds.map(td => td.innerText))

If you experience poor performance it should be another part of the script.如果您遇到性能不佳的情况,它应该是脚本的另一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM