2010-04-29 52 views

回答

0

您可以使用curl從您想要的URL中獲取html,然後解析結果以「抓取」您想要的div。

9

您可以使用PHP Simple DOM Parser來抓取頁面並輕鬆選擇其中的一部分。

一樣簡單:

$html = file_get_html('http://www.google.com/'); 
$ret = $html->find('div[id=foo]'); 

文檔here

如果你想要做的是抓住http://www.freeoh.net/的標題,下面的代碼將工作。您需要在與以下腳本相同的文件夾中放置simple_html_dom.php和一個名爲page.txt的文件(確保該腳本有權讀取和寫入該文件)。 (我假設你已經啓用捲曲,因爲你在你的問題中提到它。)

<?php 

include 'simple_html_dom.php'; 

$curl = curl_init(); 
curl_setopt ($curl, CURLOPT_URL, "http://www.freeoh.net/"); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)"); 
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); 
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($curl, CURLOPT_REFERER, "http://www.freeoh.net/"); 

$result = curl_exec ($curl); 
curl_close ($curl); 
//write contents of $result to file 
$File = "page.txt"; 
$fh = fopen($File, 'w') or die("can't open file"); 
fwrite($fh, $result); 
fclose($fh); 
//turn file into dom object 
$page = file_get_html("page.txt"); 
$header = $page->find("div", 1); 
echo $header; 

?> 

這是一個有點哈克,因爲我用捲曲抓住頁面,然後需要存儲在某個地方,使PHP簡單HTML Dom解析器會正確解析它,但它可以工作。

+0

這只是打破了網頁,例如運行此: find('div [id = header]'); ?> – James 2010-04-29 01:21:37

+0

編輯我的答案。如果您想從網站抓取標題,則代碼正在運行。 – 2010-04-29 03:32:31

+2

+1不使用正則表達式。 – SLaks 2010-04-29 13:29:51

0

按照喬治所說的那樣進行刮擦​​。
你仍然需要使用Curl和正則表達式。

+2

正則表達式將不可靠。 DOM解析器將更加可靠。 – alex 2010-04-29 03:51:28

相關問題