How do I use python variable in a javascript?

后端 未结 4 1143
再見小時候
再見小時候 2020-12-30 13:28

I\'ve been on a prowl looking for a way to access a non visible text field using selenium\'s webdriver. The only way i got it to work is using

driver.execut         


        
相关标签:
4条回答
  • 2020-12-30 13:37

    If I am understanding the problem correctly you are trying to pass a var instead of hard coded XYZ

    driver.execute_script("document.getElementById('text_field').value+='" + var + "'");
    
    0 讨论(0)
  • 2020-12-30 13:46

    The normal way to pass variables to the JavaScript code you execute through Selenium is to just pass the variables to execute_script:

    foo = "something"
    driver.execute_script("""
    var foo = arguments[0];
    document.getElementById('text_field').value += foo;
    """, foo)
    

    You retrieve the argument on the JavaScript side through the arguments object. You can do this because the code you pass to execute_script is wrapped in a function so what is executed is something like:

    function () {
        var foo = arguments[0];
        document.getElementById('text_field').value += foo;
    }
    

    and the function is called with the arguments that were passed to execute_script. The arguments are serialized automatically by Selenium.

    Interpolating with .format or concatenating strings are fragile ways to do it. For instance if you do 'var foo = "' + foo + '"' this will break as soon as your foo variable has a double quote in it (same with 'var foo = "{0}"'.format(foo)). Using json.dumps is going to avoid this and will work in most cases but it does not take care of something like this:

    el = driver.find_element(".something")
    
    // Do stuff with el on the Python side.
    
    driver.execute_script("""
    var el = arguments[0];
    // Do something with el on the JavaScript side.
    """)
    

    Selenium knows how to convert the Python object it gives you when you find an object to a DOM object on the JavaScript side. json.dumps does not do this.

    0 讨论(0)
  • 2020-12-30 13:49

    You need to obtain a JavaScript string representation of your Python variable's value, and insert that into your JavaScript command. Fortunately, Python's json module will do this for you.

    from json import dumps
    
    driver.execute_script("document.getElementById('text_field').value+=" +
                          dumps(my_python_variable))
    

    I would be wary of just inserting the value into the quote marks as other answers have shown. What if the value already has quote marks in it, or special characters that need escaping? What if it's not a string at all? json.dumps will handle all the necessary formatting and escaping for you, appropriate to the type of your variable.

    0 讨论(0)
  • 2020-12-30 13:52

    Unless I'm misisng something, one option is:

    driver.execute_script("document.getElementById('text_field').value+='{0}'".format(foo)) 
    
    0 讨论(0)
提交回复
热议问题