解析从mochiweb_html获得的结果

时间:2013-04-22 13:21:10

标签: erlang mochiweb

我想从html文件解析一些内容(没有xml)。

目前我使用mochiweb_html检索要解析的结构:

1> inets:start().
2> {ok, {Status, Headers, Body}} = httpc:request("http://www.google.com").
3> {String, Attributes, Other} = mochiweb_html:parse(Body).

结果如下:

{<<"html">>,
 [{<<"itemscope">>,<<"itemscope">>},
  {<<"itemtype">>,<<"http://schema.org/WebPage">>}],
 [{<<"head">>,[],
   [{<<"meta">>,
     [{<<"itemprop">>,<<"image">>},
      {<<"content">>,<<"/images/google_favicon_128.png">>}],
     []},
    {<<"title">>,[],[<<"Google">>]},
....

从mochiweb_http获取的结构中检索具有特定类别(例如<span id="footer">)的特定标记的所有元素的最佳方法是什么?

2 个答案:

答案 0 :(得分:6)

您可以使用mochiweb_xpath

> mochiweb_xpath:execute("//span[@id='footer']",
    mochiweb_html:parse(
      "<html><body><span>not this one</span><span id='footer'>but this one</span></body></html>")).
[{<<"span">>,
  [{<<"id">>,<<"footer">>}],
  [<<"but this one">>]}]

答案 1 :(得分:1)

这取决于您的性能要求。

mochiweb结果采用3元组形式,可能很容易转换为适合xmerl的输入。大多数工作都是将属性名称转换为原子。然后,您可以使用xmerl_xpath进行一些非常灵活的查询。

否则你可以编写一些不太灵活(但可能更快)的东西来走树。