如何在使用 Selenium 单击元素后使用 xsel 提取剪贴板内容

How to extract clipboard contents with xsel after clicking on element with Selenium

以下代码使用 Selenium and xsel 并且预计在驱动程序将网页中的某些内容复制到剪贴板后提取剪贴板内容:

import unittest
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import subprocess


class Test(unittest.TestCase):
    def run(self):
        self.driver = webdriver.Firefox()
        self.driver.get('some_uri')
        self.wait = WebDriverWait(self.driver, 20)
        link_elem = self.wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "i[data-original-title='Copy to clipboard']")))
        link_elem.click()
        self.wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "i[data-original-title='Copied']")))        
        link = subprocess.check_output(["xsel"])
        print(link)

剪贴板的内容打印出来了,但不是python代码复制的那个,而是以前剪贴板的一些内容。如何正确提取剪贴板内容?

解决方案是使用:

link = subprocess.check_output(["xsel", "--clipboard"]) 

而不是

link = subprocess.check_output(["xsel"])

来自xsel man

-b, --clipboard operate on the CLIPBOARD selection.

默认情况下 xsel 回显 PRIMARY selection 并且我需要 CLIPBOARD selection。 更多信息 here.