硒用换行符execute_script

selenium execute_script with newlines

本文关键字:script execute 换行符      更新时间:2023-09-26

我正在使用selenium和Python,我正在尝试执行一个JS函数,该函数接收如下字符串:

browser.execute_script("foo('someString')")

当某些字符串没有任何换行符时,这有效。当存在换行符时,将发生以下情况:

'n     => Parse Error
''n    => Newline is converted to a space
'r'n   => Parse Error
''r''n => Both characters are converted to a space

有没有办法做到这一点?

您可以将参数传递给 javascript;可以使用 arguments 访问这些附加参数:

browser.execute_script("foo(arguments[0])", 'someString')
browser.execute_script("foo(arguments[0])", 'string with 'n is also ok!'n')

简单的解决方案是将'n转换为 unicode 'u000a

类似的例子

driver.execute_script("document.getElementById('website_name').value='hello1'u000ahello2'")