可能重複:
How to implement a web scraper in PHP?
How to parse and process HTML with PHP?從URL獲得一個div的內容
我需要通過頁面抓取,並得到一個特定的div的內容。我有兩個主要選項的PHP和JavaScript。如何做呢?
可能重複:
How to implement a web scraper in PHP?
How to parse and process HTML with PHP?從URL獲得一個div的內容
我需要通過頁面抓取,並得到一個特定的div的內容。我有兩個主要選項的PHP和JavaScript。如何做呢?
這是一個非常基本的方法來做到這一點PHP,並將其返回以純文本的內容。不過,您可能會考慮修改正則表達式以滿足您的特定需求。
<?php
$link = file_get_contents("http://www.domain.com");
$file = strip_tags($link, "<div>");
preg_match_all("/<div/>(?:[^<]*)<\/div>/is", $file, $content);
print_r($content);
?>
具體使用jQuery,如果你有一個div
類似如下:
<div id="cool_div">Some content here</div>
您可以使用jQuery來獲取div
像這樣的內容:
$('#cool_div').text(); // will return text version of contents...
$('#cool_div').html(); // will return HTML version of contents...
如果您在使用PHP來生成頁面的內容,那麼你應該能夠獲得一個體面的內容處理,並在它返回到屏幕並顯示之前對其進行處理。希望這可以幫助!
使用PHP,你可以嘗試DOMDocument類和的getElements()函數
您可以使用SimpleDomParser作爲記錄在這裏http://simplehtmldom.sourceforge.net/manual.htm 它需要PHP5 +雖然,但好處是,你可以找到一個HTML頁面上的標籤與選擇就像jQuery的。
有很多方法可以得到一個URL的內容:
第一種方法:
http://simplehtmldom.sourceforge.net/
Simple HTML DOM Parser
第二種方法:
<?php
$contents = file_get_contents("http://www.url.com");
$contents = strip_tags($contents, "<div>");
preg_match_all("/<div/>(?:[^<]*)<\/div>/is", $contents, $file_contents);
?>
第三種方法:
`You can use jquery like Selectors :`
我知道,用正則表達式! – TJHeuvel 2012-02-01 09:02:03
你有沒有想過perl和[WWW-Mechanize](http://search.cpan.org/dist/WWW-Mechanize/)? – cctan 2012-02-01 09:05:20