繁体   English   中英

在python中使用Selenium send_keys复制文本

[英]Copying text using selenium send_keys in python

尝试使用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'

你为什么不只使用text呢?

emailID = driver.find_element_by_xpath('//*[@id="mail"]')
text_emailID = emailID.text
print(text_emailID)

更新

它似乎隐藏在JS中...所以只需使用“ Copy按钮即可!

emailID = driver.find_element_by_xpath('//*[@id="mail"]')
emailID.click()
copy_btn = driver.find_element_by_xpath('//*[@id="click-to-copy"]')
copy_btn.click()

您导入了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

切勿在自动化测试中依赖剪贴板,这是不安全的。 这些测试必须完全原子且独立,并且将数据存储在剪贴板中,这意味着您将无法使用Selenium Grid并行执行Selenium测试。

还要重新考虑使用定位器策略 ,我建议尽可能通过ID定位元素,因为这是最快,最可靠的方法。

因此,如果您运行以下代码:

driver.get("https://temp-mail.org/en/")
temp_email = driver.find_element_by_id("mail").get_attribute("value")
print(temp_email)

您应该在终端中看到临时电子邮件地址值。

暂无
暂无

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

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