如何使用selenium-webdriver和python在浏览器中的单独选项卡中打开多个网页

时间:2018-05-25 06:26:11

标签: python selenium selenium-webdriver tabs webdriver

我想使用Selenium Webdriver在Python的同一浏览器窗口中打开多个本地htmls。我曾在Jupyter笔记本中尝试过:

from selenium import webdriver

1page = "file://<path for 1.html>"
2page = "file://<path for 2.html>"
firefox_path = 'C:\geckodriver.exe'

driver = webdriver.Firefox(executable_path= firefox_path)
driver.get(1page)
# For opening 2nd HTML in another Tab
driver.execute_script('''window.open('''+ 2page + ''',"_blank");''')

运行上面的代码会导致我出现以下错误:

JavascriptException: Message: Error: Access to 'file://<path of 2.html>' from script denied

如何缓解此错误?

1 个答案:

答案 0 :(得分:2)

要在浏览器中的单独 TAB 中打开多个网址 / 网页,您可以使用以下解决方案:

  • 代码块:

    from selenium import webdriver
    
    first_page = "http://www.google.com"
    second_page = "https://www.facebook.com/" 
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument('disable-infobars')
    driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get(first_page)
    driver.execute_script("window.open('" + second_page +"');")
    
  • 浏览器快照:

multiple_tabs