Python селен неправильно выполняет закладку - PullRequest
0 голосов
/ 08 января 2020

У меня есть букмарклет, который успешно выполняется из браузера:

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

Когда я пытаюсь выполнить это через веб-драйвер Selenium, используя Python, он возвращает 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))

1 Ответ

1 голос
/ 08 января 2020

После некоторого чтения в Интернете похоже, что этот тип рабочего процесса заблокирован из-за проблем безопасности. Я видел эту ошибку в консоли 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)
...