How do I use python variable in a javascript?

后端 未结 4 1215
再見小時候
再見小時候 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: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.

提交回复
热议问题