【问题标题】:Inside HTML, URL remap library in python在 HTML 内部,python 中的 URL 重映射库
【发布时间】:2012-02-15 18:16:22
【问题描述】:

通过 URL 重新映射,我的意思是更改实际 HTML 文档中的所有“href”和“src”以及“action”和 ...。

是否有任何 python 库来执行这种类型的 URL 重新映射?

在 python 网络服务器应用程序(基于龙卷风)上,我希望能够根据某些条件修改我服务器的 HTML 代码。

想象一下,我从磁盘上读取了这些 HTML,但我需要替换所有链接和 ... 以指向这个子域/域和路径或那个。

假设我不想使用模板来重写我在磁盘上的所有 HTML(将标签放入其中并在运行时替换标签)也为了简单起见假设我没有外部链接(比如我永远不要链接到 google.com [需要有条件的重新映射])。

【问题讨论】:

    标签: python html rewrite tornado


    【解决方案1】:

    据我所知,没有这样的库,但您可以使用一些 html 解析库,如 lxmlBeautifulSoup 以及 urlparse 标准 Python moule。我更喜欢使用lxmlXPath

    例如,我们将 StackOverflow 页面保存为 doc.html,我们想要对包含 hrefsrcactions 的节点做一些事情:

    import urlparse
    
    import lxml.html
    
    
    with open('doc.htm') as f:
        doc = lxml.html.parse(f)
    
    for el in doc.xpath('//*[@href | @src | @action]'):
        tag = el.tag
        href = el.get('href', '')
        if not href:
            continue
    
        # not really need to check for '/' when using urljoin, but this is just example
        if href.startswith('/'): 
            el.attrib['href'] = urlparse.urljoin('http://stackoverflow.com/', href)
    
    # then get string representation of tree back
    result = lxml.html.tostring(doc)
    

    在此示例中,我仅将使用 urlparse.urljoin 以“/”开头的相对 href 转换为绝对,而不是使用 XPath 结果中的所有元素。但您可以根据需要对其进行自定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-04
      • 2012-10-16
      • 1970-01-01
      • 2017-07-18
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 2016-12-09
      相关资源
      最近更新 更多