首页 > 解决方案 > 在 python 中使用 selenium send_keys 复制文本

问题描述

尝试使用 selenium python 命令复制文本,但由于某种原因它似乎不起作用

这是我的代码:

driver.get('https://temp-mail.org/en/') #opens the website
emailID = driver.find_element_by_xpath('//*[@id="mail"]') #find the email ID
ActionChains = ActionChains(driver)
ActionChains.double_click(emailID).perform()
ActionChains.send_keys(keys.CONTROL + 'c').perform()

代替:

ActionChains.send_keys(keys.CONTROL + 'c').perform()

我也试过:

emailID.send_keys(keys.CONTROL + 'c')

但似乎不断收到此错误:

module 'selenium.webdriver.common.keys' has no attribute 'CONTROL'

编辑:

driver.get('https://google.com ') #opens the website
input = driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input')
ActionChains.send_keys(Keys.CONTROL + 'v').perform()

错误:

Traceback (most recent call last):
  File "C:/Users/Shadow/PycharmProjects/untitled1/venv/Test.py", line 28, in <module>
    ActionChains.send_keys(Keys.CONTROL + 'v').perform()
  File "C:\Users\Shadow\PycharmProjects\untitled1\venv\lib\site-packages\selenium\webdriver\common\action_chains.py", line 336, in send_keys
    if self._driver.w3c:
AttributeError: 'str' object has no attribute '_driver'

标签: pythonselenium

解决方案


您的错误正在发生,因为您已经导入了模块selenium.webdriver.common.keys

您应该Keys在该模块中使用该类。

from selenium.webdriver.common.keys import Keys

#...

ActionChains.send_keys(Keys.CONTROL + 'c').perform()

编辑

它实际上是将文本复制到剪贴板。您可以使用诸如pyperclip之类的库来获取文本。

from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import pyperclip
driver = Chrome('drivers/chromedriver')
driver.get('https://temp-mail.org/en/')
emailID = driver.find_element_by_xpath('//*[@id="mail"]') 
ActionChains = ActionChains(driver)
ActionChains.double_click(emailID).perform()
ActionChains.send_keys(Keys.CONTROL + 'c').perform()
text = pyperclip.paste()
print(text)

输出

caberisoj@mail-file.net

推荐阅读