当前位置: 首页 > 知识库问答 >
问题:

如何用python和selenium在新选项卡中打开链接

宇文修文
2023-03-14

我想打开我在新选项卡中找到的网站链接。我已经尝试打开一个新的标签,并将链接的url传递给这里建议的驱动程序,然而,新的标签根本不会打开。(关于如何打开新标签,还有其他几个建议,但似乎都不适合我。)

因此,我最近的尝试是右键单击链接并按“T”以在新选项卡中打开链接,如下所示:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

# Using Firefox to access web
driver = webdriver.Firefox()

# Open the website
driver.get('https://registers.esma.europa.eu/publication/searchRegister?core=esma_registers_firds')

# search for information
elem = driver.find_element_by_id('keywordField')
elem.clear()
elem.send_keys('XS1114155283')

button = driver.find_element_by_id('searchSolrButton')
button.click()

table_body = driver.find_element_by_xpath("//table[@id='T01']/tbody")
for link in table_body.find_elements_by_tag_name('a'):

    act = ActionChains(driver)
    act.context_click(link)
    act.send_keys("t")
    act.perform()

    # ... do something in the new tab, close tab, and open next link ...
MoveTargetOutOfBoundsException: (974, 695) is out of bounds of viewport width (1366) and height (654)

共有1个答案

东方华晖
2023-03-14

可以使用driver.execute_script()函数在新选项卡中打开链接

from selenium import webdriver

# Using Firefox to access web

driver = webdriver.Firefox()

# Open the website
driver.get('https://registers.esma.europa.eu/publication/searchRegister?core=esma_registers_firds')

# search for information
elem = driver.find_element_by_id('keywordField')
elem.clear()
elem.send_keys('XS1114155283')

button = driver.find_element_by_id('searchSolrButton')
button.click()

table_body = driver.find_element_by_xpath("//table[@id='T01']/tbody")
for link in table_body.find_elements_by_tag_name('a'):
    href = link.get_attribute('href')
    # open in new tab
    driver.execute_script("window.open('%s', '_blank')" % href)
    # Switch to new tab
    driver.switch_to.window(driver.window_handles[-1])

    # Continuous your code
 类似资料:
  • 请告知如何使用Python selenium Chrome WebDriver在新选项卡中打开链接。所以,我不是在问如何简单地打开一个新标签,也不是在问如何用Firefox打开一个新标签。 此选项卡将在新选项卡中打开相同的页面: 因此,当试图通过Selenium或requests访问此元素的链接时,它将重定向到搜索结果本身的页面。有鉴于此,我决定用一种不同的方法来解决这个问题。 因此,我决定放弃在

  • 问题内容: 新标签页正在打开,但URL链接未打开。 问题答案: 我检查了以下代码,它对我来说很好。我从这里找到了答案。

  • 所以我试图在我的WebDriver中打开新的标签页。我想这样做,因为打开一个新的WebDriver为每个网站使用PhantomJS约3.5秒,我想要更快... 我使用的是一个多进程python脚本,我希望从每个页面中获取一些元素,因此工作流如下所示:

  • 我看过很多答案 Selenium IDE:在新选项卡中打开并将焦点转移到新选项卡不工作 如何在新选项卡中打开链接等...关于这个问题的帖子,但没有一个是100%相关的,所以,我再次问这个。我需要在三个不同的选项卡中打开三个不同的链接:

  • 我有一个每行都有一个URL的文本文档。我希望每个URL都在一个新选项卡中打开。这是我到目前为止所拥有的: 这给了我一个错误: 回溯(最近一次调用last):驱动程序中第100行的文件“scraper.py”。execute\u script(“window.open(url,'new\u window')”)文件“C:\Python37\lib\site packages\selenium\web

  • 问题内容: 如何使用Selenium WebDriver(又名Selenium 2)在现有的Firefox浏览器中打开新标签页? 问题答案: 以下代码将在新标签页中打开链接。 下面的代码将打开空白的新标签页。