[英]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.
我不确定如何进行调试,因为我对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
: 您正在一个接一个地执行三个JavaScript代码段,在第二个代码段中,您期望定义了变量
x
,但并未定义,因此得到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. 并让硒驱动程序执行它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.