解析HTML并保留原始内容

时间:2012-07-20 09:18:49

标签: python html ruby node.js html-parsing

我有很多HTML文件。我想替换一些元素,保持所有其他内容不变。例如,我想执行这个jQuery表达式(或者它的一些等价物):

$('.header .title').text('my new content')

在以下HTML文档中:

<div class=header><span class=title>Foo</span></div>
<p>1<p>2
<table><tr><td>1</td></tr></table>

并得到以下结果:

<div class=header><span class=title>my new content</span></div>
<p>1<p>2
<table><tr><td>1</td></tr></table>

问题是,我尝试过的所有解析器(NokogiriBeautifulSouphtml5lib)都将其序列化为:

<html>
  <head></head>
  <body>
    <div class=header><span class=title>my new content</span></div>
    <p>1</p><p>2</p>
    <table><tbody><tr><td>1</td></tr></tbody></table>
  </body>
</html>

E.g。他们补充说:

  1. html,头部和身体元素
  2. 关闭p标签
  3. TBODY
  4. 是否有满足我需求的解析器​​?它应该在Node.js,Ruby或Python中工作。

7 个答案:

答案 0 :(得分:11)

我强烈推荐用于python的pyquery包。它是一个类似jquery的接口,位于极其可靠的lxml包的顶部,是一个绑定到libxml2的python。

我相信这完全符合您的要求,并且有一个非常熟悉的界面。

from pyquery import PyQuery as pq
html = '''
<div class=header><span class=title>Foo</span></div>
<p>1<p>2
<table><tr><td>1</td></tr></table>
'''
doc = pq(html)

doc('.header .title').text('my new content')
print doc

输出:

<div><div class="header"><span class="title">my new content</span></div>
<p>1</p><p>2
</p><table><tr><td>1</td></tr></table></div>

关闭p标签无法提供帮助。 lxml仅保留原始文档中的,而不是原始文档的变幻莫测。段落可以有两种方式,它在进行序列化时选择更标准的方式。我不相信你会找到一个更好的(无错误)解析器。

答案 1 :(得分:6)

注意:我在Python 3上。

这只会处理CSS选择器的一个子集,但它可能足以满足您的需要。

from html.parser import HTMLParser

class AttrQuery():
    def __init__(self):
        self.repl_text = ""
        self.selectors = []

    def add_css_sel(self, seltext):
        sels = seltext.split(" ")

        for selector in sels:
            if selector[:1] == "#":
                self.add_selector({"id": selector[1:]})
            elif selector[:1] == ".":
                self.add_selector({"class": selector[1:]})
            elif "." in selector:
                html_tag, html_class = selector.split(".")
                self.add_selector({"html_tag": html_tag, "class": html_class})
            else:
                self.add_selector({"html_tag": selector})

    def add_selector(self, selector_dict):
        self.selectors.append(selector_dict)

    def match_test(self, tagwithattrs_list):
        for selector in self.selectors:
            for condition in selector:
                condition_value = selector[condition]
                if not self._condition_test(tagwithattrs_list, condition, condition_value):
                    return False
        return True

    def _condition_test(self, tagwithattrs_list, condition, condition_value):
        for tagwithattrs in tagwithattrs_list:
            try:
                if condition_value == tagwithattrs[condition]:
                    return True
            except KeyError:
                pass
        return False


class HTMLAttrParser(HTMLParser):
    def __init__(self, html, **kwargs):
        super().__init__(self, **kwargs)
        self.tagwithattrs_list = []
        self.queries = []
        self.matchrepl_list = []
        self.html = html

    def handle_starttag(self, tag, attrs):
        tagwithattrs = dict(attrs)
        tagwithattrs["html_tag"] = tag
        self.tagwithattrs_list.append(tagwithattrs)

        if debug:
            print("push\t", end="")
            for attrname in tagwithattrs:
                print("{}:{}, ".format(attrname, tagwithattrs[attrname]), end="")
            print("")

    def handle_endtag(self, tag):
        try:
            while True:
                tagwithattrs = self.tagwithattrs_list.pop()
                if debug:
                    print("pop \t", end="")
                    for attrname in tagwithattrs:
                        print("{}:{}, ".format(attrname, tagwithattrs[attrname]), end="")
                    print("")
                if tag == tagwithattrs["html_tag"]: break
        except IndexError:
            raise IndexError("Found a close-tag for a non-existent element.")

    def handle_data(self, data):
        if self.tagwithattrs_list:
            for query in self.queries:
                if query.match_test(self.tagwithattrs_list):
                    line, position = self.getpos()
                    length = len(data)
                    match_replace = (line-1, position, length, query.repl_text)
                    self.matchrepl_list.append(match_replace)

    def addquery(self, query):
        self.queries.append(query)

    def transform(self):
        split_html = self.html.split("\n")
        self.matchrepl_list.reverse()
        if debug: print ("\nreversed list of matches (line, position, len, repl_text):\n{}\n".format(self.matchrepl_list))

        for line, position, length, repl_text in self.matchrepl_list:
            oldline = split_html[line]
            newline = oldline[:position] + repl_text + oldline[position+length:]
            split_html = split_html[:line] + [newline] + split_html[line+1:]

        return "\n".join(split_html)

请参阅下面的示例用法。

html_test = """<div class=header><span class=title>Foo</span></div>
<p>1<p>2
<table><tr><td class=hi><div id=there>1</div></td></tr></table>"""

debug = False
parser = HTMLAttrParser(html_test)

query = AttrQuery()
query.repl_text = "Bar"
query.add_selector({"html_tag": "div", "class": "header"})
query.add_selector({"class": "title"})
parser.addquery(query)

query = AttrQuery()
query.repl_text = "InTable"
query.add_css_sel("table tr td.hi #there")
parser.addquery(query)

parser.feed(html_test)

transformed_html = parser.transform()
print("transformed html:\n{}".format(transformed_html))

输出:

transformed html:
<div class=header><span class=title>Bar</span></div>
<p>1<p>2
<table><tr><td class=hi><div id=there>InTable</div></td></tr></table>

答案 2 :(得分:4)

好的我用几种语言完成了这个,我不得不说我见过的最好的解析器保留了空格,甚至是HTML注释:

Jericho ,遗憾的是 Java

这就是杰里科知道如何解析和保存碎片。

是的,我知道它的Java,但是你可以轻松地使用一小部分Java来实现RESTful服务,这需要有效负载并进行转换。在Java REST服务中,您可以使用JRuby,Jython,Rhino Javascript等与Jericho协调。

答案 3 :(得分:2)

您可以使用Nokogiri HTML Fragment:

fragment = Nokogiri::HTML.fragment('<div class=header><span class=title>Foo</span></div>
                                    <p>1<p>2
                                    <table><tr><td>1</td></tr></table>')

fragment.css('.title').children.first.replace(Nokogiri::XML::Text.new('HEY', fragment))

frament.to_s #=> "<div class=\"header\"><span class=\"title\">HEY</span></div>\n<p>1</p><p>2\n</p><table><tr><td>1</td></tr></table>" 

p标记的问题仍然存在,因为它是无效的HTML,但这应该返回没有html,head或body和tbody标记的文档。

答案 4 :(得分:1)

使用 Python - 使用lxml.html非常简单: (它符合第1点和第3点,但我认为不能对2做很多事情,并处理不带引号的class=

import lxml.html

fragment = """<div class=header><span class=title>Foo</span></div>
<p>1<p>2
<table><tr><td>1</td></tr></table>
"""

page = lxml.html.fromstring(fragment)
for span in page.cssselect('.header .title'):
    span.text = 'my new value'
print lxml.html.tostring(page, pretty_print=True)

结果:

<div>
<div class="header"><span class="title">my new content</span></div>
<p>1</p>
<p>2
</p>
<table><tr><td>1</td></tr></table>
</div>

答案 5 :(得分:0)

这是一个稍微独立的解决方案,但如果这仅适用于几个简单的实例,那么CSS就是答案。

Generated Content

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
  <head>
    <style type="text/css">
    #header.title1:first-child:before {
      content: "This is your title!";
      display: block;
      width: 100%;
    }
    #header.title2:first-child:before {
      content: "This is your other title!";
      display: block;
      width: 100%;
    }
    </style>

  </head>
  <body>
   <div id="header" class="title1">
    <span class="non-title">Blah Blah Blah Blah</span>
   </div>
  </body>
</html>

在这种情况下,您可以让jQuery交换类,并且您可以使用css免费获得更改。我没有测试过这种特殊用法,但它应该可行。

我们将此用于中断消息等内容。

答案 6 :(得分:0)

如果您正在运行Node.js应用程序,此模块将完全按照您的需要执行,即JQuery样式DOM操纵器:https://github.com/cheeriojs/cheerio

来自他们wiki的一个例子:

var cheerio = require('cheerio'),
$ = cheerio.load('<h2 class="title">Hello world</h2>');

$('h2.title').text('Hello there!');
$('h2').addClass('welcome');

$.html();
//=> <h2 class="title welcome">Hello there!</h2>