dongle19863 2012-07-04 04:56
浏览 33
已采纳

从html中提取信息?

First of all, I've seen a good deal of similar questions. I know regex or dom can be used, but I can't find any good examples of DOM and regex makes me pull my hair. In addition, I need to pull out multiple values from the html source, some simply contents, some attributes.

Here is an example of the html I need to get info from:

<div class="log">
    <div class="message">
        <abbr class="dt" title="time string">
            DATA_1
        </abbr>
        :
        <cite class="user">
            <a class="tel" href="tel:+xxxx">
                <abbr class="fn" title="DATA_2">
                    Me
                </abbr>
            </a>
        </cite>
        :
        <q>
            DATA_3
        </q>
    </div>
</div>

The "message" block may occur once or hundreds of times. I am trying to end up with data like this:

array(4) {
    [0] => array(3) {
               ["time"] => "DATA_1"
               ["name"] => "DATA_2"
               ["message"] => "DATA_3"
           }
    [1] => array(3) {
               ["time"] => "DATA_1"
               ["name"] => "DATA_2"
               ["message"] => "DATA_3"
           }
    [2] => array(3) {
               ["time"] => "DATA_1"
               ["name"] => "DATA_2"
               ["message"] => "DATA_3"
           }
    [3] => array(3) {
               ["time"] => "DATA_1"
               ["name"] => "DATA_2"
               ["message"] => "DATA_3"
           }
}

I tried using simplexml but it only seems to work on very simple html pages. Could someone link me to some examples? I get really confused since I need to get DATA_2 from a title attribute. What do you think is the best way to extract his data? It seems very similar to XML extraction which I have done, but I need to use some other method.

  • 写回答

2条回答 默认 最新

  • drex88669 2012-07-04 05:28
    关注

    Here is an example using DOMDocument and DOMXpath to parse your HTML.

    $doc = new DOMDocument;
    $doc->loadHTMLFile('your_file.html');
    $xpath = new DOMXpath($doc);
    
    $res = array();
    
    foreach ($xpath->query('//div[@class="message"]') as $elem) {
        $res[] = array(
            'time' => $xpath->query('abbr[@class="dt"]', $elem)->item(0)->nodeValue,
            'name' => $xpath->query('cite/a/abbr[@class="fn"]', $elem)->item(0)->getAttribute('title'),
            'message' => $xpath->query('q', $elem)->item(0)->nodeValue,
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值