[英]What does execute_script() in Selenium does
browser.execute_script("window.open('about:blank', 'tab2');")
browser.switch_to.window("tab2")
browser.get('http://bing.com')
我在網上搜索在 python 中使用 selenium 打開新選項卡的方法,而ctrl + t的方法在 chrome 上不起作用,所以我偶然發現了上面的代碼,但是我無法理解 'excute_script' 的作用.
execute_script()在當前窗口/框架中同步執行JavaScript 。
execute_script(script, *args)
where:
script: The JavaScript to execute
*args: Any applicable arguments for your JavaScript.
該方法定義為:
def execute_script(self, script, *args):
"""
Synchronously Executes JavaScript in the current window/frame.
:Args:
- script: The JavaScript to execute.
- \\*args: Any applicable arguments for your JavaScript.
:Usage:
::
driver.execute_script('return document.title;')
"""
if isinstance(script, ScriptKey):
try:
script = self.pinned_scripts[script.id]
except KeyError:
raise JavascriptException("Pinned script could not be found")
converted_args = list(args)
command = None
if self.w3c:
command = Command.W3C_EXECUTE_SCRIPT
else:
command = Command.EXECUTE_SCRIPT
return self.execute(command, {
'script': script,
'args': converted_args})['value']
幾個例子:
要打開一個新的空白選項卡:
driver.execute_script("window.open('','_blank');")
要打開帶有 url 的新標簽頁:
driver.execute_script("window.open('https://www.google.com');")
要檢索頁面標題:
driver.execute_script('return document.title;')
要滾動初始視圖元素:
driver.execute_script("arguments[0].scrollIntoView(true);",element)
您可以在以下位置找到一些相關的詳細討論:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.