[英]JavaScriptException in execute_script method
def send(self, message):
try:
textArea = self.driver.find_element_by_xpath("//textarea[@placeholder='Message...']")
textArea.clear()
self.driver.execute_script("arguments[0].value='" + message + "'", textArea) # Error right here
textArea.send_keys(Keys.SPACE)
sendButton = self.driver.find_element_by_xpath("//button[contains(text(), 'Send')]").click()
except NoSuchElementException or StaleElementReferenceException as ex:
print("Исключение в send()")
print(ex)
Up to this point, the fifth line worked, but now I just can't figure out what the problem is.到目前为止,第五行有效,但现在我无法弄清楚问题出在哪里。 And the variables have correct values.
并且变量具有正确的值。
File "D:\PROJECTS\BLD_Project\main.py", line 187, in send
self.driver.execute_script("arguments[0].value='" + message + "'", textArea)
File "D:\PROJECTS\INST\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 878, in execute_script
return self.execute(command, {
File "D:\PROJECTS\INST\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "D:\PROJECTS\INST\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.JavascriptException: Message: javascript error: Unexpected identifier
Assuming message
is a string, you can use setAttribute
inside execute_script
like below:假设
message
是一个字符串,您可以在execute_script
中使用setAttribute
,如下所示:
textArea = self.driver.find_element_by_xpath("//textarea[@placeholder='Message...']")
self.driver.execute_script(f"arguments[0].setAttribute('value', '{message}')", textArea)
to pass message
variable into textArea
web element.将
message
变量传递到textArea
web 元素。
You seem to be running into escaping troubles.您似乎遇到了 escaping 麻烦。 If
message
contains a quote character, for example O'Hara
, you'd end up with a syntax error in the executed JavaScript code:如果
message
包含引号字符,例如O'Hara
,您将在执行的 JavaScript 代码中出现语法错误:
arguments[0].value='O'Hara'
The solution is to use the arguments
array that you're already using, to pass the message
string as well:解决方案是使用您已经在使用的
arguments
数组来传递message
字符串:
self.driver.execute_script("arguments[0].value = arguments[1]", textArea, message)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.