2011-06-11 3 views
2

가능한 중복 :
Parse Website for URLsPHP에서 웹 페이지의 링크 목록을 얻는 방법은 무엇입니까?

어떻게 웹 페이지의 모든 링크가 PHP를 사용합니까?

나는 링크의 목록을 얻을 필요가 : -

Google

나는 HREF (http://www.google.com)과 텍스트 (구글)

을 인출 할 --- ---------------- 상황은 다음과 같습니다. -

크롤러를 만들고 데이터베이스 테이블에있는 모든 링크를 가져 오려고합니다.

답변

6

는이 작업을 수행하는 몇 가지 방법이 있습니다,하지만 난이 다음과 같은 것입니다 접근하는 방법과,

cURL을 사용하여 페이지, 즉 가져 : 모든된다면

// $target_url has the url to be fetched, ie: "http://www.website.com" 
// $userAgent should be set to a friendly agent, sneaky but hey... 

$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)'; 
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); 
curl_setopt($ch, CURLOPT_URL,$target_url); 
curl_setopt($ch, CURLOPT_FAILONERROR, true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); 
curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
$html = curl_exec($ch); 
if (!$html) { 
echo "<br />cURL error number:" .curl_errno($ch); 
echo "<br />cURL error:" . curl_error($ch); 
exit; 
} 

을 글쎄, 페이지 내용은 이제 모두 $ html로되어 있습니다.

$dom = new DOMDocument(); 
@$dom->loadHTML($html); 

지금까지 너무 좋아, DOM 객체에서 링크를 긁어 할 수있는 구조로의 XPath :

$xpath = new DOMXPath($dom); 
$hrefs = $xpath->evaluate("/html/body//a"); 

루프

의이 이동하고 DOM 개체에서 페이지를로드하자 그 결과를 통해 다음 링크를 얻으십시오 :

for ($i = 0; $i < $hrefs->length; $i++) { 
$href = $hrefs->item($i); 
$link = $href->getAttribute('href'); 
$text = $href->nodeValue 

    // Do what you want with the link, print it out: 
    echo $text , ' -> ' , $link; 

    // Or save this in an array for later processing.. 
    $links[$i]['href'] = $link; 
    $links[$i]['text'] = $text;       
} 

$ hrefs는 DOMNodeList 유형의 객체이고 item()은 D 지정된 인덱스의 OMNode 객체 기본적으로 각 링크를 DOMNode 객체로 가져 오는 루프가 있습니다.

이것은 꽤 많이해야 할 일입니다. 링크가 이미지 또는 앵커 인 경우 100 % 확신 할 수없는 유일한 부분은 이러한 상황에서 어떤 일이 벌어 지는지, 테스트 할 필요가 없다는 것입니다.

희망이 있으면 링크를 해독하고 행복한 코딩을하는 방법에 대한 아이디어를 얻을 수 있습니다.

관련 문제