Skip to content Skip to main navigation Skip to footer

Python: python模块介绍-webbrowser:方便的web浏览器控制器

目录

源码:Lib/webbrowser.py

简介

webbrowser模块提供了展示基于web文档的高层接口。多数情况下, 简单地调用open() 函数即可。

在Unix的X11下,首选调用图形浏览器。如果图形浏览器不可用或者没有显示终端,则使用文本模式浏览器 。如果使用文本模式浏览器, 在用户退出浏览器之前调用进程都会阻塞。

如果设置了BROWSER环境变量,它将覆盖平台默认的浏览器列表。 BROWSER是os.pathsep分割的的浏览器列表。如果列表的部分值包含字符串“%s”,解析为浏览器命令行的参数。

对于非Unix平台或unix使用远程浏览器时, 控制进程不会等待用户完成浏览, 但允许远程浏览器显示自己的窗口 。如没有远程浏览器, 控制进程将发起新的浏览器并等待。

webbrowser支持命令行接口。 它接受URL作为参数。可选参数:“-n”在新的浏览窗口打开URL;“-t”打开新的tab。

$ python -m webbrowser -t "http://automationtesting.sinaapp.com/blog/url"
andrew@andrew-Hi-Fi-A88S2:~$ [4860:4860:0520/095513:ERROR:url_pattern_set.cc(240)] Invalid url pattern: chrome://print/*
[4897:4897:0520/095513:ERROR:sandbox_linux.cc(343)] InitializeSandbox() called with multiple threads in process gpu-process
andrew@andrew-Hi-Fi-A88S2:~$
andrew@andrew-Hi-Fi-A88S2:~$ python -m webbrowser -t "http://automationtesting.sinaapp.com/blog/url"
andrew@andrew-Hi-Fi-A88S2:~$ 已在现有的浏览器会话中创建新的窗口。
andrew@andrew-Hi-Fi-A88S2:~$

快速入门

import webbrowser
webbrowser.open('http://automationtesting.sinaapp.com')
webbrowser.open_new_tab('http://automationtesting.sinaapp.com/blog/url')

上例会打开两个标签。

接口介绍

  • 异常:exception webbrowser.Error: 当浏览器控制错误时抛出该异常。

函数

  • webbrowser.open(url, new=0, autoraise=True)

使用默认的浏览器访问url。如果new等于0,则url会在尽量在已有浏览器窗口打开。如果new等于1, 则打开新的浏览器窗口。new等于2,尽量在浏览器打开新标签(tab)。如果autoraise为True,则浏览器窗口显示在最前面(注意在多数窗口管理器会这样)。

注意在某些平台上,打开文件名的时候 ,可能会启动系统的关联程序。另外一些系统默认用最节省资源的方式打开浏览器。

  • webbrowser.open_new(url)

使用默认的浏览器打开url,尽量只有一个窗口

  • webbrowser.open_new_tab(url)

使用默认的浏览器的新tab中打开url。

  • webbrowser.get([name])

返回制定浏览器控制器对象。如果name为空,则返回默认浏览器的控制器。

  • webbrowser.register(name, constructor, instance=None)

注册浏览器类型:name。注册后get() 函数可以返回该浏览器类型的控制器 。如果instance没有提供或者是None, 构造函数可以无参数调用并创建实例。如果有提供instance, 就不会调用构造函数。

This entry point is only useful if you plan to either set the BROWSER variable or call get() with a nonempty argument matching the name of a handler you declare.

仅仅在设置BROWSER变量或使用非空参数调用get()时有效。 你声明一个处理程序的名称相匹配的。

预定义的浏览器类型

浏览器控制器对象

  • controller.open(url, new=0, autoraise=True)
  • controller.open_new(url)
  • controller.open_new_tab(url)

请参考模块函数文档。

本文地址

原文:http://automationtesting.sinaapp.com/blog/m_webbrowser

0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.