我在 CDP 模式下使用SeleniumBase 。
我很难弄清楚这是 Python 问题还是 SeleniumBase 问题。
下面的简单示例显示了我的问题:
from seleniumbase import SB
with SB(uc=True, locale_code="en", headless=True) as sb:
link = "https://news.ycombinator.com"
print(f"\nOpening {link}")
sb.wait_for_ready_state_complete(timeout=120)
sb.activate_cdp_mode(link)
script = f"""
function getSomeValue() {{
return '42';
}}
return getSomeValue();
"""
# data = sb.execute_script(script)
data = sb.cdp.evaluate(script)
print(data)
print("Finished!")
这会引发错误:
seleniumbase.undetected.cdp_driver.connection.ProtocolException:
exceptionId: 1
text: Uncaught
lineNumber: 5
columnNumber: 4
scriptId: 6
exception:
type: object
subtype: error
className: SyntaxError
description: SyntaxError: Illegal return statement
objectId: 3089353218542582072.1.2
请注意,我已经尝试了两者sb.execute_script(script)
,sb.cdp.evaluate(script)
并且都出现了同样的问题。
我如何执行此类脚本?
return
在 CDP 模式下,评估 JS 时不要包含 final 。你的脚本部分看起来应该是这样的:
(而不是使用
"return getSomeValue();"
,这会破坏evaluate(expression)
。)