javascript - php 抓取的頁面如何處理可以只保留DOM結構,去掉CSS和JS?

來源:互聯網
上載者:User
正則規則寫好後,頁面一旦有改變就要重新修改正則。
先提取頁面的 DOM,有沒有比較好的辦法?

回複內容:

正則規則寫好後,頁面一旦有改變就要重新修改正則。
先提取頁面的 DOM,有沒有比較好的辦法?

我想你需要的是 php 的 DOM 模組 ... 預設有安裝不用擔心 ...

因為不知道你的實際應用情境是什麼 ... 給你寫個簡單的例子吧 ...

loadHTML( <<Sunyanzi's Test  

Hello World

Hey WelcomeHTML_SECTION);/* now we should try to get something ... */$h1Elements = $doc->getElementsByTagName( 'h1' );/* this line prints "Hello World" ... */foreach( $h1Elements as $h1Node ) echo $h1Node->nodeValue, PHP_EOL;/* and this line prints "http://segmentfault.com/" ... */echo $doc->getElementById( 'onlylink' )->getAttribute( 'href' ), PHP_EOL;/* now i will introduce something advanced ... using XPath ... */$xpath = new DOMXPath( $doc );/* also prints "http://segmentfault.com/" ... locate via h1 ... */echo $xpath->evaluate( 'string(//h1[text()="Hello World"]/following-sibling::a/@href)' ), PHP_EOL;

基本上 ... 等到你熟練掌握 XPath 之後 ... 你會發現 DOM 比正則要靈活得多 ...

php 處理 XML 的能力遠遠超乎你的想象 ... 有空讀讀手冊不是壞事恩 ...

你說的很對。我現在就用xpath。。。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.