在主选项卡的Web元素中嵌入了一个链接,我想使用SeleniumWebdriver和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()
I expect the link in div[data-res-position = '1']
to open in a new tab
由于在“ 父选项卡”的web元素中嵌入了一个链接,要使用Selenium和Python在同一窗口的“ 新选项卡”中
打开该链接,您可以使用以下 解决方案:
为了证明该URL的工作流程https://www.google.com/在打开
的父选项卡,然后open in new tabfunctionalty实现
通过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()
Note : You need to replace (By.LINK_TEXT, "Gmail")
with your desired locator e.g. ("div[data-res-position = '1']")
Browser Snapshot:
You can find a relevant Java based solution in Opening a new tab using
Ctrl + click combination in Selenium
Webdriver
要将Selenium的重点转移到新打开的选项卡上,可以在Selenium + Python的新选项卡的Open web中找到详细的讨论。