【问题标题】:Parsing the result obtained from mochiweb_html解析从 mochiweb_html 得到的结果
【发布时间】:2013-04-23 17:57:10
【问题描述】:

我想从一个 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 获得的结构中检索网页中具有特定标签和特定类的所有元素的最佳方法是什么(例如,&lt;span id="footer"&gt;)?

【问题讨论】:

    标签: erlang mochiweb


    【解决方案1】:

    你可以使用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">>]}]
    

    【讨论】:

      【解决方案2】:

      这取决于您的性能要求。

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

      否则,您可以编写一些不太灵活(但可能更快)的代码来遍历树。

      【讨论】:

      • 真的。只需在树上行走即可从中获取所需的东西。
      • 你能举个例子吗?我被卡住了:(
      • 我更喜欢@legoscia 提供的解决方案。我不知道 mochiweb_xpath。
      猜你喜欢
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多