4

I am deploying some JavaScript on a page with selenium's driver.execute_script function.

I prepare my JavaScript but if I drop the code into another line like so:

script = 'line one code' +
         'line two code'
driver.execute_script(script)

It gives me an error. I've also tried doing:

script = [
    'line one code',
    'line two code'
]
script = ';'.join(script)

But that gave me same error.

2 Answers 2

5

To construct a multi-line script, you can take help of the triple quotes i.e. """ ... """.

Here is a example of multi-line script which is invoked through execute_script() using 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)

You can call the method as:

wheel_element(elm, -120)
Sign up to request clarification or add additional context in comments.

2 Comments

In the case of executing the Script for driver.execute_script(), is it different? I see you are doing it into an element
Triple quotes didn't work for me (Selenium, NodeJs, webdriver) so I have to put code into this quotation code . These special quotes ( ` ) worked for me only.
0

Add \ after the + sign

script = 'line one code ' + \
         'line two code'

Or use round brackets

script = ('line one code '
          'line two code')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.