[英]method execute_script don't wait end of script to return value with selenium in python
i'm trying to make a bot follow for instagram with python and selenium. 我正在尝试使用python和硒使bot跟随instagram。 (I am not a developer javascript or python.)
(我不是开发人员的javascript或python。)
Anyway, i would like return an array of user with js in execute_script. 无论如何,我想在execute_script中返回一个带有js的用户数组。
and get it with a return in js script. 并在js脚本中返回它。
my python code : 我的python代码:
ole = []
ole = driver.execute_script("dd = document.getElementsByClassName(\"_8mlbc _t5r8b\"); i = 9; ret = []; before = 0; function need_up() { before = document.getElementsByClassName(\"_4zhc5 _ook48\")[0].title; } function loveu() { if (i == dd.length){return ret;} dd[i].click(); b = setTimeout(need_up, 300);ret.push(before); i++; a = setTimeout(loveu, 400);} return loveu();")
for readability here is the javascript code indented : 为了提高可读性,此处是缩进的javascript代码:
dd = document.getElementsByClassName("_8mlbc _t5r8b");
i = 9;
ret = [];
before = 0;
function get_name_user() {
before = document.getElementsByClassName("_4zhc5 _ook48")[0].title;
}
function get_array_user()
{
if (i == dd.length){
return ret;
}
dd[i].click();
b = setTimeout(get_name_user, 500);
ret.push(before);
i++;
a = setTimeout(get_array_user, 500);
}
get_array_user();
return ret;
You can try this code on this url (for exemple) , it works ONLY on firefox: https://www.instagram.com/explore/tags/happy/ 您可以在此url上尝试此代码(例如) ,它仅在firefox上有效: https : //www.instagram.com/explore/tags/happy/
Thank you 谢谢
The root cause is you call a = setTimeout(loveu, 400);
根本原因是您调用
a = setTimeout(loveu, 400);
asynchronously, so it returns immediately. 异步,因此它立即返回。 I think you need to read how to use setTimeout http://javascript.info/tutorial/settimeout-setinterval .
我认为您需要阅读如何使用setTimeout http://javascript.info/tutorial/settimeout-setinterval 。
I have revised your code by calling a = loveu();
我已经通过调用
a = loveu();
修改了您的代码a = loveu();
instead of a = setTimeout(loveu, 400);
而不是
a = setTimeout(loveu, 400);
and move it into function need_up()
. 并将其移入
function need_up()
。
ole = []
script = """
dd = document.getElementsByClassName("_8mlbc _t5r8b");
i = 9; ret = []; before = 0;
function need_up() {
before = document.getElementsByClassName("_4zhc5 _ook48")[0].title;
ret.push(before);
i++;
a = loveu();
}
function loveu() {
if (i == dd.length){return ret;}
dd[i].click();
b = setTimeout(need_up, 5000);
}
return loveu();
"""
ole = driver.execute_script(script)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.