使用Python在Firefox中打开几个标签 [英] Opening several tabs in Firefox using Python

查看:194
本文介绍了使用Python在Firefox中打开几个标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花大约一分钟的时间输入通常在早上检查到Firefox的10到15个站点的名称.这是我的时间的相当大的"浪费,那么为什么不自动化该过程呢?在Firefox启动时打开每个选项卡不是一个好的解决方案(因为我只检查一次这些页面一次),所以我认为一个小的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)

url_list.txt文件仅使用换行符分隔页面的URL.

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

我面临的问题是此脚本的行为取决于我是否已经启动了Firefox.如果Firefox正在运行,则列出的URL将按预期在单独的选项卡中打开.如果Firefox没有运行,则每个URL将在单个窗口中打开,这会中断我的工作流程.为什么会这样?

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?

推荐答案

webbrowser在后台工作的方式包括创建subprocess.Popen对象.这具有两个潜在影响,它们直接与报告的结果相对应:

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:

  • 如果Firefox已打开,则webbrowser检测到Firefox已在运行,它将正确的参数发送到Popen,这将在当前Firefox窗口中打开每个URL.

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

如果不存在Firefox进程,则发生的情况是正在向Firefox发出多个并发请求以访问传递的URL.由于不存在任何窗口,因此无法创建选项卡,Firefox的最后一个选择是在单独的窗口中显示每个链接.

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.

我设法通过在调用Firefox时简单地加入所有URL来解决了这个问题.尽管这样做有一定的局限性(指命令字符串的字符数限制),但这是一个非常简单有效的解决方案:

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)

这篇关于使用Python在Firefox中打开几个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆