猿问

如何在 selenium 中使用多行脚本来执行脚本

我正在使用 selenium 的 driver.execute_script 函数在页面上部署一些 JavaScript。


我准备了我的 JavaScript 但如果我将代码放到另一行中,如下所示:


script = 'line one code' +

         'line two code'

driver.execute_script(script)

它给了我一个错误。我也试过这样做:


script = [

    'line one code',

    'line two code'

]

script = ';'.join(script)

但这给了我同样的错误。


繁星coding
浏览 202回答 2
2回答

慕哥6287543

要构建多行脚本,您可以借助三重引号ie """ ... """。这是通过execute_script()使用Selenium调用的多行脚本示例:def wheel_element(element, deltaY = 120, offsetX = 0, offsetY = 0):  error = element._parent.execute_script("""    var element = arguments[0];    var deltaY = arguments[1];    var box = element.getBoundingClientRect();    var clientX = box.left + (arguments[2] || box.width / 2);    var clientY = box.top + (arguments[3] || box.height / 2);    var target = element.ownerDocument.elementFromPoint(clientX, clientY);    for (var e = target; e; e = e.parentElement) {      if (e === element) {        target.dispatchEvent(new MouseEvent('mouseover', {view: window, bubbles: true, cancelable: true, clientX: clientX, clientY: clientY}));        target.dispatchEvent(new MouseEvent('mousemove', {view: window, bubbles: true, cancelable: true, clientX: clientX, clientY: clientY}));        target.dispatchEvent(new WheelEvent('wheel',     {view: window, bubbles: true, cancelable: true, clientX: clientX, clientY: clientY, deltaY: deltaY}));        return;      }    }        return "Element is not interactable";    """, element, deltaY, offsetX, offsetY)您可以将方法调用为:wheel_element(elm, -120)

慕斯709654

\在+符号后添加script = 'line one code ' + \         'line two code'或者使用圆括号script = ('line one code '          'line two code')
随时随地看视频慕课网APP

相关分类

Python
我要回答