如何将已复制的 URL 粘贴到新选项卡中 Python Selenium

问题描述 投票:0回答:2

我正在测试一个网站,它会自动复制 URL,我需要将复制的 URL 粘贴到新选项卡中,我已尝试以下操作,但这不起作用。请问有什么建议吗?

    self.driver.find_element(By.ID, "getLink").click()   << the URL is copied when you click this link
    self.driver.execute_script("window.open('about:blank','_blank');")
    new_tab = self.driver.window_handles[1]
    self.driver.switch_to.window(new_tab)
    pyperclip.paste()
python selenium-webdriver pycharm
2个回答
0
投票

这是我当前的解决方法:

from selenium.webdriver.common.keys import Keys

# Click the link to copy the URL
self.driver.find_element(By.ID, "getLink").click()

# Open a new tab
self.driver.execute_script("window.open('https://www.webfx.com/tools/url-opener/','_blank');")

# Switch to the new tab
new_tab = self.driver.window_handles[1]
self.driver.switch_to.window(new_tab)

# Find the address bar and paste the URL
urls = self.driver.find_element(By.CSS_SELECTOR, "#urls")
urls.send_keys(Keys.CONTROL + 'v')

# Press Enter to open
address_bar.send_keys(Keys.ENTER)

0
投票

您可以将输出存储在

pyperclip.paste()
的变量中,并将其作为字符串参数传递到
window.open

self.driver.find_element(By.ID, "getLink").click() 
result = pyperclip.paste()
driver.execute_script(f"window.open('{result}')")

使用示例:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pyperclip

driver = webdriver.Chrome()

driver.get("https://inputnum.w3spaces.com/saved-from-Tryit-2024-01-24.html")
wait = WebDriverWait(driver, 20)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "button[onclick='myFunction()']"))).click()
result = pyperclip.paste()
driver.execute_script(f"window.open('{result}')")
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.