【问题标题】:How to open a link in a new tab with python and selenium如何使用 python 和 selenium 在新选项卡中打开链接
【发布时间】:2019-05-19 18:31:02
【问题描述】:

我想在新标签中打开在网站上找到的链接。我试图打开一个新选项卡并将链接的 url 传递给驱动程序,如建议的 here,但是,新选项卡根本不会打开。 (关于如何打开一个新标签,还有其他一些建议,但它们似乎都不适合我。)

所以我最近的尝试是右键单击链接并按“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 ...

但是,我在act.perform() 上收到一条错误消息,内容为

MoveTargetOutOfBoundsException: (974, 695) is out of bounds of viewport width (1366) and height (654)

我通过在新窗口中打开链接来解决问题,但我更喜欢选项卡版本,因为打开新浏览器窗口而不是新选项卡需要更长的时间。

【问题讨论】:

  • 您能否提供正确的Instrument identification code,我们在XS1114155283 的搜索结果中没有收到任何详细信息。
  • @supputuri 这是一个有效的 ISIN。该网站在几个小时前似乎无法正常运行。

标签: python selenium selenium-webdriver


【解决方案1】:

您可以使用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

【讨论】:

  • 这很好用,谢谢。但它会打开一个新窗口,而不是一个新选项卡。并不是说这很重要,但出于好奇,知道如何打开一个新标签吗?另外,知道为什么右键单击链接不起作用吗?
  • 我在 Chrome 上测试了这段代码,因为 Firefox 给了我一个例外。尝试添加参数_blank:driver.execute_script("window.open('%s', '_blank')" % href) 并检查是否有效。关于右键单击,我无法解释为什么不起作用,我说的唯一建议是尽可能避免使用 selenium 模拟鼠标事件,总是很头疼。
  • _blankarguemnt 没有效果。
  • 没关系,我之前的评论。看来这方面的讨论有点徒劳,见here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-19
  • 2019-12-07
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多