我想在新标签页中打开在网站上找到的链接。我试图打开一个新的标签和链接的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 ...
但是,我收到一条错误消息act.perform()
,内容为
MoveTargetOutOfBoundsException: (974, 695) is out of bounds of viewport width (1366) and height (654)
我通过在新窗口中打开链接来解决问题,但我真的更喜欢标签版本,因为打开新浏览器窗口而不是新标签需要更长的时间。
您可以使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句