gpt4 book ai didi

javascript - 使用 selenium Nodejs 等待异步函数

转载 作者:行者123 更新时间:2023-12-04 07:31:07 29 4
gpt4 key购买 nike

我正在创建一个小程序,当您使用 selenium 在 google 上搜索某些内容时,它会返回所有链接标题的名称
这是代码:

const {Builder,By, Key, until} = require('selenium-webdriver');

driver = new Builder().forBrowser("firefox").build();

var search_query='tigers';

(async()=>{

await driver.get(`https://www.google.com/search?q=${search_query}`);

await driver.findElements(By.css('h3')).then((search_results)=>{
for (var i = 0; i < search_results.length; i++)
search_results[i].getText().then((text)=>{console.log(text);})
});

console.log('...Task Complete!')
})();
当你运行它时,输出如下:-
...Task Complete!
Tiger - Wikipedia
Top stories
Tigers (2014 film) - Wikipedia
Detroit Tigers (@tigers) · Twitter
Tiger | Species | WWF
Videos
Official Detroit Tigers Website | MLB.com
Tiger | WWF
Tiger - National Geographic Kids
Tiger guide: species facts, how they hunt and where to see in ...
Related searches
Images
Description

很明显 ...Task Complete!应在整个功能完成后记录
我不明白我做错了什么我使用了适当的 await保持代码流有序的关键字,是 then()中的错误?

最佳答案

由于您的 .then(()=>...)不返回 promise ,await开头的关键字没有任何作用。 Node 已经开始 promise 获取 h3,获取它们的文本内容并记录它们,但是你放错了 await不会告诉 Node 等待所有这些完成。你会想要 await获取元素,然后同步遍历所有元素,await输入文本,然后同步打印文本,最后同步打印"...Task Complete!"

const { Builder, By, Key, until } = require('selenium-webdriver');

const driver = new Builder().forBrowser("firefox").build();

const search_query = 'tigers';

(async () => {
await driver.get(`https://www.google.com/search?q=${search_query}`);

const h3Elements = await driver.findElements(By.css('h3'));
for (const h3 of h3Elements) {
const text = await h3.getText();
console.log(text);
}

console.log('...Task Complete!')
})();
如果你想减少额外的变量,你可以这样做:
const { Builder, By, Key, until } = require('selenium-webdriver');

const driver = new Builder().forBrowser("firefox").build();

const search_query = 'tigers';

(async () => {
await driver.get(`https://www.google.com/search?q=${search_query}`);

const h3Elements = await driver.findElements(By.css('h3'));
for (const h3 of h3Elements) {
console.log(await h3.getText());
}

console.log('...Task Complete!')
})();

关于javascript - 使用 selenium Nodejs 等待异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67927085/

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