Home > Enterprise >  Which way to run javascript code in a python loop is more efficient?
Which way to run javascript code in a python loop is more efficient?

Time:10-20

I'm executing JavaScript code in python selenium while loop script, what would be the fastest way this loop could run? python while-loop:

while not k.is_pressed('key'):
   driver.execute_script(js_code)

js_code (Is looking for one button 'btn1', when it is available it clicks it and then another button should appear 'btn2' - click it too):

js_code = ''' function clickBtn2(){
let btn2 = document.querySelector(selector-btn2)
btn2.click()
}
function clickBtn1(){
let btn1 = document.querySelector(selector-btn1)
if (btn1){
btn1.click()
}
try{
        clickBtn2()
    }
    catch (err){}
}
clickBtn1()
'''

Would it run faster using js code this way?:

try{
   document.querySelector(selector-btn1).click()
}catch(err){}
try{
   document.querySelector(selector-btn2).click()
}catch(err){}

Iam looking for performance, need to look as many times as possible for both buttons in some time and click them, the btn2 is available in short load-depended time after clicking the first button.

Also I use key to break out of the while loop, using just simple

While True:

Would probably boost the performance more?

CodePudding user response:

This will click on whichever is available and not raise an error if they're both missing

document.querySelector(".btn1,.btn2")?.click()
  • Related