Python硒无法正确执行小书签

问题描述 投票:0回答:1

我有一个从浏览器成功执行的小书签:

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通过Selenium Webdriver执行此操作时,它返回None。关于如何使文本像小书签一样复制到剪贴板的任何想法?完整代码如下:

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))
python selenium clipboard bookmarklet
1个回答
0
投票

经过一些在线阅读后,发现此类型的工作流程由于安全问题而被阻止。我在控制台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)
© www.soinside.com 2019 - 2024. All rights reserved.