How to open a link in a new tab with python and selenium

主宰稳场 提交于 2021-01-07 03:14:12

问题


I want to open links that I find on a website in a new tab. I have tried to open a new tab and pass the url of the link to the driver as suggested here, however, the new tab simply will not open. (There are a couple of other suggestion for how to open a new tab, but none of them seem to work for me.)

So my latest attempt was to right-click the link and press "t" to open the link in a new tab, like so:

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 ...

However, I get an error message on act.perform() which reads

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

I managed a work around by opening the link in a new window, but I would really prefer the tab-version, as it would take longer to open a new browser window rather than a new tab.


回答1:


You can use driver.execute_script() function to open link in a new tab

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


来源:https://stackoverflow.com/questions/56210820/how-to-open-a-link-in-a-new-tab-with-python-and-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!