14

我有很多 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>

例如,他们添加:

  1. html、head 和 body 元素
  2. 关闭 p 标签
  3. 身体

是否有满足我需求的解析器​​?它应该可以在 Node.js、Ruby 或 Python 中运行。

4

7 回答 7

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只保留原始文档中的,而不是原始文档的变幻莫测。段落可以有两种方式,在进行序列化时选择更标准的方式。我不相信你会找到一个更好的(无错误的)解析器。

于 2012-07-20T16:20:30.790 回答
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>
于 2012-08-11T18:14:29.120 回答
4

好的,我已经用几种语言做到了这一点,我不得不说我见过的保留空格甚至 HTML 注释的最好的解析器是:

Jericho不幸的是Java

那就是 Jericho 知道如何解析和保存片段。

是的,我知道它的 Java,但您可以使用一点点 Java 轻松创建一个 RESTful 服务,该服务将获取有效负载并进行转换。在 Java REST 服务中,您可以使用 JRuby、Jython、Rhino Javascript 等与 Jericho 进行协调。

于 2012-08-16T19:46:06.880 回答
2

您可以为此使用 Nokogiri HTML 片段:

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 标签的文档。

于 2012-07-20T16:01:27.263 回答
1

使用Python - 使用lxml.html相当简单:(它符合第 1 点和第 3 点,但我认为关于第 2 点可以做的不多,并处理未引用class=的 's)

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>
于 2012-07-20T16:33:53.620 回答
0

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

生成的内容

<!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 免费获得更改。我还没有测试过这种特殊的用法,但它应该可以工作。

我们将其用于诸如中断消息之类的事情。

于 2012-08-15T16:50:40.640 回答
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>
于 2015-05-12T15:48:26.640 回答