簡體   English   中英

如何使用 Control + Click of Selenium Webdriver 在同一窗口的新選項卡中的主選項卡中打開嵌入在 webelement 中的鏈接

[英]How to open a link embeded in a webelement with in the main tab, in a new tab of the same window using Control + Click of Selenium Webdriver

在主選項卡的 web 元素中嵌入了一個鏈接,我想使用 Selenium Webdriver 和 python 在同一窗口的新選項卡中打開該鏈接。 在新選項卡中執行一些任務,然后關閉該選項卡並返回主選項卡。 我們將通過右鍵單擊鏈接手動執行此操作,然后選擇“在新選項卡中打開”以在新選項卡中打開該鏈接。

我是硒的新手。 我正在使用 Selenium 和 BeautifulSoup 進行網頁抓取。 我只知道如何點擊鏈接。 我已經閱讀了很多帖子,但找不到正確的答案

url = "https://www.website.com"
path = r'path_to_chrome_driver'
drive = webdriver.Chrome(path)
drive.implicitly_wait(30)
drive.get(url)
source = drie.page_source

py_button = driver.find_element_by_css_selector("div[data-res-position = '1']")
py_button.click()

我希望div[data-res-position = '1']的鏈接在新選項卡中打開

以下導入:

selenium.webdriver.common.keys import Keys

您必須發送密鑰:

py_button.send_keys(Keys.CONTROL + 't')

如果您的定位器返回正確的href則可以實現此技巧。

先試試這個:

href = driver.find_element_by_css_selector("div[data-res-position = '1']").get_attribute("href")
print(href)

如果你得到正確的href ,你可以這樣做:

#handle current tab
first_tab = driver.window_handles[0]

#open new tab with specific url
driver.execute_script("window.open('" +href +"');")

#hadle new tab
second_tab = driver.window_handles[1]

#switch to second tab
driver.switch_to.window(second_tab)

#switch to first tab
driver.switch_to.window(first_tab)

希望這可以幫助。

由於在Parent Tab的 webelement 中嵌入了一個鏈接,要使用SeleniumPython在同一窗口中的New Tab中打開鏈接,您可以使用以下解決方案:

為了證明該URL的工作流程https://www.google.com/父選項卡打開,然后open in new tab functionalty通過實施ActionChains方法key_down()click()key_up()方法。

  • 代碼塊:

     from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys import time options = webdriver.ChromeOptions() options.add_argument("start-maximized") driver = webdriver.Chrome(options=options, executable_path=r'C:\\WebDrivers\\chromedriver.exe') driver.get("https://www.google.com/") link = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Gmail"))) ActionChains(driver).key_down(Keys.CONTROL).click(link).key_up(Keys.CONTROL).perform()
  • 注意:您需要將(By.LINK_TEXT, "Gmail")替換為所需的定位器,例如("div[data-res-position = '1']")

  • 瀏覽器快照:

tab_actions

您可以在使用 Ctrl + 單擊組合在 Selenium Webdriver打開新選項卡中找到相關的基於Java的解決方案


更新

要將 Selenium 的重點轉移到新打開的選項卡,您可以在新選項卡 Selenium + Python中的Open web 中找到詳細討論

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM