【问题标题】:How to get style attributes and line number of htm elements?如何获取html元素的样式属性和行数?
【发布时间】:2016-01-25 17:22:51
【问题描述】:

我尝试了以下方法,但它不能正常工作,它给了我各种标签,还有没有样式属性的标签。

  1. 使用 curl() 加载网站
  2. 将 html 正文从 curl 添加到名为:$bodyhtml 的变量中
  3. 使用 preg_match_all 查找页面上的所有样式属性,但未按预期工作。

我的 preg_match_all:

preg_mathc_all = preg_match_all('/(<[^>]+) style=".*?"/i', $bodyhtml, $matches);

获取样式属性值的最佳方法是什么,如果可能的话,在文档中找到它的行是什么?

【问题讨论】:

  • 简单。不要使用正则表达式。 DOM 的存在是有原因的,就是这样......
  • 与其使用正则表达式,为什么不使用DOMDocument 也可能使用DOMXPath 来做到这一点——可能更简单
  • 谢谢你会这样看。你知道如何通过 DOM 获取文档中元素的行吗?有没有可能。 ?
  • 没有,afaik,一个内置函数可以直接做到这一点,但它应该很容易完成

标签: php css attributes web-crawler


【解决方案1】:

感谢到目前为止的帮助。 我最终使用了 DOM,并且工作正常 :) 谢谢!

我一直在尝试找到一个函数/类,它可以在文档中找到 DOM 或 HTML 字符串中的行。

但到目前为止还没有运气。

有人有好的方法吗?

【讨论】:

    【解决方案2】:

    说了“这应该很容易完成”,我想我应该试一试,但现在不得不承认它并不像我最初想象的那么简单。以下内容已接近尾声,有人( OP )可能希望花一些时间来研究它,看看可以改进的地方。

    notes/cmets 的方式很少,所以我可能会因此而被否决,但我把它留在这里,希望 op 可以让它更准确(离我们不远了!)

    $url='http://stackoverflow.com/questions/34998468/how-to-get-style-attributes-and-line-number-of-htm-elements#34998468';
    $tmp=tempnam( sys_get_temp_dir(), 'html' );
    file_put_contents( $tmp, file_get_contents( $url ) );
    
    $dom=new DOMDocument;
    $dom->loadHTMLFile( $tmp );
    
    $xp=new DOMXPath( $dom );/* the xpath query could be improved */
    $col=$xp->query( '//*[@style]', $dom->getElementsByTagName('body')->item(0) );
    
    if( $col ){
        $data=array();
        /* iterate through nodes found by xpath query */
        foreach( $col as $node ){
            $tag=$node->tagName;
            $value=$node->nodeValue;
            $style=$node->getAttribute('style');
            /* create array for later use */
            $data[]=(object)array( 'tag'=>$tag, 'style'=>$style, 'html'=>trim( strip_tags( $value ) ) );
        }
    
        /* connect to the new file */
        $spl=new SplFileObject( $tmp );
    
        /* iterate through array found from xpath */
        foreach( $data as $key => $obj ){
            $str=$obj->html;
            $i=1;
    
            if( !empty( $str ) && strlen( $str ) > 1 ){/* ignore empty strings */
                $spl->fseek( 0 );
    
                while( !$spl->eof() ) {/* read the html source file line by line + make matches */
                    if( stristr( $spl->fgetss(), $str ) ) {
                        echo 'line: '.$i.', tag: '.$obj->tag.', html:'.$str.', style:'.$obj->style.BR;
                        break;  
                    }
                    $i++;
                }
            }
        }
    }
    @unlink( $tmp );
    $dom = $xp = $col = $spl = $tmp = null;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 2023-03-25
      • 2020-04-14
      • 2015-02-24
      • 2023-03-14
      • 2012-06-01
      相关资源
      最近更新 更多