Python selenium未正确执行bookmarklet

2024-09-29 18:41:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从浏览器成功执行的bookmarklet:

javascript:!function(a){var b=document.createElement("textarea"),c=document.getSelection();b.textContent= a,document.body.appendChild(b),c.removeAllRanges(),b.select(),document.execCommand("copy"),c.removeAllRanges(),document.body.removeChild(b);}(<text here>);

当我尝试使用Python通过SeleniumWebDriver执行此操作时,它将返回None。有没有想过如何让它像bookmarklet一样将文本复制到剪贴板?完整代码如下:

from selenium import webdriver

chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=chromeOptions, desired_capabilities=chromeOptions.to_capabilities())
driver.implicitly_wait(5)

driver.get("websitehere")

js = """javascript:!function(a){var b=document.createElement("textarea"),c=document.getSelection();b.textContent= a,document.body.appendChild(b),c.removeAllRanges(),b.select(),document.execCommand("copy"),c.removeAllRanges(),document.body.removeChild(b);}(<texthere>);
"""

print(driver.execute_script(js))

Tags: vardriverfunctionbodyjavascriptdocumentwebdrivertextarea
1条回答
网友
1楼 · 发布于 2024-09-29 18:41:56

在线阅读一段时间后,由于安全问题,此类工作流程似乎被阻止。我在控制台中看到这个错误chrome document.execCommand(‘cut’/‘copy’) was denied because it was not called from inside a short running user-generated event handler.

请注意,以下内容在Firefox上不起作用,只有Chrome可能在下几个版本的Chrome上出现故障

from selenium import webdriver
import time
import pyperclip
import pyautogui


driver = webdriver.Chrome(executable_path=r'C:\\Path\\To\\chromedriver.exe')
driver.get("https://www.google.com")
time.sleep(2)
pyautogui.hotkey('ctrl', 'shift', 'j')
time.sleep(2)

js2 = """
var testCopy = function(a) {
var b=document.createElement("textarea"), c=document.getSelection();
b.textContent = a,
document.body.appendChild(b)
c.removeAllRanges()
b.setAttribute("id", "testid")
b.select()
document.execCommand("copy")
console.log('copy success', document.execCommand('copy'));
c.removeAllRanges();
}

testCopy("ThisText")

"""

driver.execute_script(js2)
time.sleep(1)
a = pyperclip.paste()
print(a)

相关问题 更多 >

    热门问题