python - 如何使用 python 和 selenium 在新选项卡中打开链接
问题描述
我想在新选项卡中打开在网站上找到的链接。我已尝试打开一个新选项卡并将链接的 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
推荐阅读
- python-3.x - 使用 BeautifulSoup 代码审查进行网页抓取
- reactjs - react-redux 中的 CRUD,显示来自另一个页面的帖子详细信息
- ios - dispatch_sync 永远不会从块中返回
- python - Python,XML发送带有格式的POST请求
- jquery - Rails 中的 Masonry Jquery - 不刷新页面就无法工作
- swift - swift中的抽象类和抽象函数
- javascript - 在 netbeans 中使用 node.js 从 mysql db 添加值以选择表单
- android - Android webview阻止evaluateJavascript
- django - 如何知道 django 中任何 GCBV 返回的上下文数据?
- javascript - 从另一个组件单击按钮时如何刷新一个组件(导航栏)?