Python中的WebBrowser库与HTML字符串格式化

目录


Webbrowser库

概述

webbrowser是Python标准库中的一个模块,提供了在浏览器中打开网页的高级接口。它允许你使用系统默认浏览器或其他可用浏览器打开URL。

基本用法

1. 打开网页

import webbrowser

# 使用默认浏览器打开网页
webbrowser.open('https://www.python.org')

# 在新标签页中打开(如果浏览器支持)
webbrowser.open_new_tab('https://www.github.com')

# 在新窗口中打开(如果浏览器支持)
webbrowser.open_new('https://www.google.com')

2. 指定浏览器

import webbrowser

# 获取可用的浏览器类型
print(webbrowser._browsers)

# 使用特定浏览器
webbrowser.get('firefox').open('https://www.python.org')
webbrowser.get('chrome').open('https://www.github.com')

主要函数

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

  • 参数
  • url: 要打开的网址
  • new: 控制打开方式
    • 0: 在现有浏览器窗口中打开
    • 1: 在新浏览器窗口中打开
    • 2: 在新标签页中打开
  • autoraise: 是否将窗口提到前台

webbrowser.open_new(url)

在新窗口中打开URL(如果可能)

webbrowser.open_new_tab(url)

在新标签页中打开URL(如果可能)

webbrowser.get(using=None)

获取指定浏览器的控制器对象

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

注册浏览器类型

高级用法

1. 注册自定义浏览器

import webbrowser

# 注册自定义浏览器路径
chrome_path = 'C:/Program Files/Google/Chrome/Application/chrome.exe %s'
webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chrome_path))

# 使用自定义浏览器
webbrowser.get('chrome').open('https://www.python.org')

2. 在不同平台上的使用

import webbrowser
import platform

def open_url_smart(url):
    system = platform.system()

    if system == "Windows":
        # Windows系统
        webbrowser.open(url)
    elif system == "Darwin":
        # macOS系统
        webbrowser.open(url)
    elif system == "Linux":
        # Linux系统
        webbrowser.get('firefox').open(url)
    else:
        webbrowser.open(url)

open_url_smart('https://www.python.org')

3. 批量打开多个网页

import webbrowser
import time

urls = [
    'https://www.python.org',
    'https://www.github.com',
    'https://stackoverflow.com'
]

for url in urls:
    webbrowser.open_new_tab(url)
    time.sleep(1)  # 延迟1秒,避免同时打开太多标签页

实际应用示例

1. 简单的网页启动器

import webbrowser

class WebLauncher:
    def __init__(self):
        self.bookmarks = {
            'python': 'https://www.python.org',
            'github': 'https://www.github.com',
            'stackoverflow': 'https://stackoverflow.com',
            'google': 'https://www.google.com'
        }

    def open_site(self, site_name):
        if site_name in self.bookmarks:
            webbrowser.open(self.bookmarks[site_name])
            print(f"正在打开: {site_name}")
        else:
            print(f"未找到书签: {site_name}")

    def add_bookmark(self, name, url):
        self.bookmarks[name] = url
        print(f"已添加书签: {name} -> {url}")

    def list_bookmarks(self):
        print("可用书签:")
        for name, url in self.bookmarks.items():
            print(f"  {name}: {url}")

# 使用示例
launcher = WebLauncher()
launcher.open_site('python')
launcher.list_bookmarks()

2. 搜索工具

import webbrowser

class SearchTool:
    @staticmethod
    def google_search(query):
        url = f"https://www.google.com/search?q={query.replace(' ', '+')}"
        webbrowser.open(url)

    @staticmethod
    def youtube_search(query):
        url = f"https://www.youtube.com/results?search_query={query.replace(' ', '+')}"
        webbrowser.open(url)

    @staticmethod
    def github_search(query):
        url = f"https://github.com/search?q={query.replace(' ', '+')}"
        webbrowser.open(url)

# 使用示例
SearchTool.google_search("Python webbrowser tutorial")
SearchTool.youtube_search("Python programming")

3. 文档查看器

import webbrowser
import os

class DocumentationViewer:
    def __init__(self):
        self.docs_base_url = "https://docs.python.org/3/library/"

    def open_module_docs(self, module_name):
        url = f"{self.docs_base_url}{module_name}.html"
        webbrowser.open(url)

    def search_docs(self, search_term):
        url = f"https://docs.python.org/3/search.html?q={search_term.replace(' ', '+')}"
        webbrowser.open(url)

# 使用示例
viewer = DocumentationViewer()
viewer.open_module_docs("webbrowser")
viewer.search_docs("open function")

注意事项

  1. 跨平台兼容性: webbrowser模块在Windows、macOS和Linux上都能工作,但行为可能略有不同。

  2. 浏览器可用性: 如果指定的浏览器不可用,会抛出webbrowser.Error异常。

  3. 后台打开: 使用BackgroundBrowser可以在后台打开浏览器,不会将窗口提到前台。

  4. 安全性: 在Web应用程序中使用时要小心,避免打开任意URL导致安全风险。

错误处理示例

import webbrowser

def safe_open(url, browser='default'):
    try:
        if browser == 'default':
            webbrowser.open(url)
        else:
            webbrowser.get(browser).open(url)
        return True
    except webbrowser.Error as e:
        print(f"无法打开浏览器: {e}")
        return False
    except Exception as e:
        print(f"发生错误: {e}")
        return False

# 使用示例
safe_open('https://www.python.org')
safe_open('https://www.python.org', 'firefox')

HTML字符串格式化

基本格式化方法

使用 html 模块

import html

html_string = '<div class="container"><h1>Title</h1><p>This is a paragraph</p></div>'

# 转义HTML特殊字符(安全显示)
escaped = html.escape(html_string)
print("转义后的HTML:")
print(escaped)

# 取消转义(如果字符串被转义过)
# unescaped = html.unescape(escaped_string)

使用 pprint 格式化

import pprint

html_string = '<div class="container"><h1>Title</h1><p>This is a paragraph</p></div>'

print("使用pprint格式化:")
pprint.pprint(html_string)

使用BeautifulSoup

from bs4 import BeautifulSoup

html_string = '<div class="container"><h1>Title</h1><p>This is a paragraph</p></div>'

# 使用BeautifulSoup格式化HTML
soup = BeautifulSoup(html_string, 'html.parser')
formatted_html = soup.prettify()

print("使用BeautifulSoup格式化:")
print(formatted_html)

使用lxml

from lxml import etree, html as lxml_html

html_string = '<div class="container"><h1>Title</h1><p>This is a paragraph</p></div>'

# 使用lxml格式化
parsed = lxml_html.fromstring(html_string)
formatted = lxml_html.tostring(parsed, pretty_print=True, encoding='unicode')

print("使用lxml格式化:")
print(formatted)

自定义格式化函数

import re

def format_html(html_string, indent_size=4):
    """自定义HTML格式化函数"""
    indent = 0
    formatted_lines = []

    # 分割HTML标签和内容
    lines = re.split(r'(<[^>]*>)', html_string)

    for line in lines:
        if not line.strip():
            continue

        if line.startswith('</'):
            indent -= 1
            formatted_lines.append(' ' * (indent * indent_size) + line)
        elif line.startswith('<') and not line.startswith('<!') and not '/>' in line and not line.endswith('/>'):
            formatted_lines.append(' ' * (indent * indent_size) + line)
            if not line.startswith('<?') and not line.startswith('<!') and not '/>' in line and not line.endswith('/>'):
                indent += 1
        else:
            formatted_lines.append(' ' * (indent * indent_size) + line)
            if line.strip().startswith('</'):
                indent -= 1

    return '\n'.join(formatted_lines)

# 使用示例
html_string = '<div class="container"><h1>Title</h1><p>This is a paragraph with <strong>bold</strong> text.</p></div>'
print("自定义格式化:")
print(format_html(html_string))

在Jupyter中显示

from IPython.display import HTML, display

html_string = '<div class="container" style="border: 1px solid #ccc; padding: 10px;"><h1 style="color: blue;">Title</h1><p>This is a paragraph</p></div>'

# 在Jupyter中渲染HTML
display(HTML(html_string))

# 同时显示源代码和渲染结果
print("HTML源代码:")
print(html_string)
print("\n渲染结果:")
display(HTML(html_string))

语法高亮显示

from pygments import highlight
from pygments.lexers import HtmlLexer
from pygments.formatters import TerminalFormatter, HtmlFormatter

html_string = '''
<!DOCTYPE html>
<html>
<head>
    <title>示例页面</title>
    <style>
        body { font-family: Arial; }
        .container { margin: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>欢迎</h1>
        <p>这是一个段落</p>
    </div>
</body>
</html>
'''

# 在终端中语法高亮
highlighted = highlight(html_string, HtmlLexer(), TerminalFormatter())
print("语法高亮显示:")
print(highlighted)

# 生成HTML格式的语法高亮
html_highlighted = highlight(html_string, HtmlLexer(), HtmlFormatter())
with open('highlighted.html', 'w', encoding='utf-8') as f:
    f.write(html_highlighted)

完整示例

def display_html_advanced(html_string, method='beautifulsoup'):
    """
    高级HTML显示函数
    method: 'beautifulsoup', 'lxml', 'custom'
    """
    print("原始HTML:")
    print(repr(html_string))
    print("\n" + "="*50 + "\n")

    if method == 'beautifulsoup':
        try:
            from bs4 import BeautifulSoup
            soup = BeautifulSoup(html_string, 'html.parser')
            formatted = soup.prettify()
            print("BeautifulSoup格式化:")
            print(formatted)
        except ImportError:
            print("请安装BeautifulSoup: pip install beautifulsoup4")

    elif method == 'lxml':
        try:
            from lxml import html as lxml_html
            parsed = lxml_html.fromstring(html_string)
            formatted = lxml_html.tostring(parsed, pretty_print=True, encoding='unicode')
            print("lxml格式化:")
            print(formatted)
        except ImportError:
            print("请安装lxml: pip install lxml")

    elif method == 'custom':
        formatted = format_html(html_string)
        print("自定义格式化:")
        print(formatted)

# 使用示例
html_content = '<html><head><title>Test</title></head><body><div><p>Hello World</p></div></body></html>'
display_html_advanced(html_content, method='beautifulsoup')

安装依赖

# 安装常用的HTML处理库
pip install beautifulsoup4 lxml html5lib

# 如果需要语法高亮
pip install pygments

# 如果在Jupyter中使用
pip install ipython

选择建议

选择哪种方法取决于你的具体需求: - 简单显示: 使用 pprint 或自定义函数 - 严格格式化: 使用 BeautifulSouplxml - 在Jupyter中: 使用 IPython.display - 语法高亮: 使用 pygments - 安全显示: 使用 html.escape()


文档整理完成时间: 2025-10-07