playwright-python执行js自定义方法
之前在Selenium里执行js方法很简单,现在切换到playwright上,发现原来执行js的方式不起作用了,在MSEDGE里执行
Selenium里执行JS
driver.execute_script('''function st() { var height = document.body.clientHeight; if(height > 10000){ var number = 0; var length = 0; var frequency = 15; var time = setInterval(function(){ number += 1; if(number == frequency + 1){ clearInterval(time); } else { length += height / frequency; document.documentElement.scrollTop = length; } },800); }else{ var number = 0; var length = 0; var frequency = 12; var time = setInterval(function(){ number += 1; if(number == frequency + 1){ clearInterval(time); } else { length += height / frequency; document.documentElement.scrollTop = length; } },800); } } st();''')
playwright 里执行JS的方法是 evaluate,如果要执行上述js方法,需要对其进行修改
page.evaluate("""() => { var height = document.body.clientHeight; var windowHeight = document.documentElement.clientHeight; var scrollTop = document.documentElement.scrollTop; if(height > 10000){ var number = 0; var length = 0; var frequency = 50; var time = setInterval(function(){ height = document.body.clientHeight; scrollTop = document.documentElement.scrollTop; if(windowHeight + scrollTop >= height){ clearInterval(time); } else { length += 500; document.documentElement.scrollTop = length; } },1500); }else{ var number = 0; var length = 0; var frequency = 50; var time = setInterval(function(){ height = document.body.clientHeight; scrollTop = document.documentElement.scrollTop; if(windowHeight + scrollTop >= height){ clearInterval(time); } else { length += 500; document.documentElement.scrollTop = length; } },1500); } }""")
修改后能够正常执行JS操作