Doktoro Reichard
Doktoro Reichard

Reputation: 597

Opening several tabs in Firefox using Python

I spend about a minute typing the names of the 10 to 15 sites I usually check first thing in the morning into Firefox. This is a "considerable" waste of my time, so why not automate the process? Having every tab open at the Firefox startup isn't a good solution (because I only check those pages once) so I thought a little Python script should do the trick:

import webbrowser
with open('url_list.txt', 'r') as url_file:
    for url in url_file:
        webbrowser.open(url)

The url_list.txt file only has the pages' URLs separated by newlines.

The problem I face is that the behavior of this script depends on whether I have already started Firefox. If Firefox is running, the listed URL's will open in separate tabs, as intended. If Firefox isn't running though, every single URL will open in a single window, which breaks my workflow. Why is this happening?

Upvotes: 1

Views: 3658

Answers (3)

Kuladip
Kuladip

Reputation: 154

driver = webdriver.Ie("C:\\geckodriver.exe")
binary = FirefoxBinary('usr/bin/firefox') # Optional
driver = webdriver.Firefox(firefox_binary=binary) # Optional
driver.get("http://www.google.com")
driver.maximize_window()

Upvotes: 1

Tom
Tom

Reputation: 1326

A way to do it without hard-coding the browser path is to open the first one, wait a few seconds, and then open the rest:

import webbrowser, time
with open('url_list.txt', 'r') as url_file:
    urls = [line.strip() for line in url_file]
webbrowser.open(urls[0])
time.sleep(4)
for url in urls[1:]:
    webbrowser.open_new_tab(url)

Upvotes: 1

Doktoro Reichard
Doktoro Reichard

Reputation: 597

The way webbrowser works in the background consists of creating subprocess.Popen objects. This has two underlying effects that map directly with the reported results:

  • If Firefox is open, as webbrowser detects that Firefox is already running, it sends the correct argument to Popen, which results in every URL opening in the current Firefox window.

  • If no Firefox process exists, then what happens is that several concurrent requests are being made to Firefox to access the passed URLs. As no window exists, there isn't a way to create tabs and the last option Firefox has is to present every link in a separate window.

I managed to solve this problem by simply joining all URL's while calling Firefox. This has certain limitations though (referent to the character limit of a command string) but it is a very simple and efficient solution:

import subprocess
firefox_path = "C:/Program Files/Mozilla Firefox/firefox.exe"
cmdline = [firefox_path]
with open('url_list.txt', 'r') as url_file:
    for url in url_file:
        cmdline.append(url)
subprocess.Popen(cmdline)

Upvotes: 2

Related Questions