简体   繁体   中英

Executing JavaScript in Python With Selenium

I'm currently trying to remove attributes of an element on a webpage I'm automating. There will always be two variables with that name and the second one will always be the one that needs to be modified.

Does this all need to be executed at once in order to work? Or do I need to add the element as an argument? I'm unsure how to go about debugging this because I'm not extremely familiar with JavaScript.

The following is my current code:

js_one = "var x = document.getElementsByName(\"element\")"
js_two = "x[1].removeAttribute(\"readonly\")"
js_three = "x[1].removeAttribute(\"disabled\")"

driver.execute_script(js_one)
driver.execute_script(js_two)
driver.execute_script(js_three)

It gives me the following error:

  File "main.py", line 393, in main
    driver.execute_script(js_two)
  File "C:\Users\~\AppData\Local\Continuum\anaconda3\lib\site-packages\sele
nium\webdriver\remote\webdriver.py", line 629, in execute_script
    'args': converted_args})['value']
  File "C:\Users\~\AppData\Local\Continuum\anaconda3\lib\site-packages\sele
nium\webdriver\remote\webdriver.py", line 314, in execute
    self.error_handler.check_response(response)
  File "C:\Users\~\AppData\Local\Continuum\anaconda3\lib\site-packages\sele
nium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.JavascriptException: Message: ReferenceError: x is no
t defined

EDIT I solved the issue by changing my code to the following:

js_one = 'document.getElementsByName("element")[1].removeAttribute("readonly");' 
js_two = 'document.getElementsByName("element")[1].removeAttribute("disabled");'
driver.execute_script(js_one + js_two)      

If anybody has a more efficient way to carry this out, please feel free to let me know!

You are executing three JavaScript snippets one after another, and in your second snippet you expect variable x to be defined, which it isn't, hence you get the ReferenceError :

selenium.common.exceptions.JavascriptException: Message: ReferenceError: x is not defined

I'd suggest trying it like this:

driver.execute_script(";".join([js_one, js_two, js_three]))

This will join your individual snippets to a single one using ; and has the selenium driver execute it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM