繁体   English   中英

Python selenium 未正确执行书签

[英]Python selenium not executing bookmarklet properly

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

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))

经过一些在线阅读后,由于安全问题,这种类型的工作流程似乎被阻止了。 我在控制台chrome document.execCommand('cut'/'copy') was denied because it was not called from inside a short running user-generated event handler.中看到了这个错误, 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM