[英]python selenium send_keys CONTROL, 'c' not copying actual text
[英]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.