2010-07-30 8 views
5

예를 들어, 웹 페이지에서 많은 링크가 제공됩니다.cURL을 사용하여 링크를 클릭하는 방법?

forward backward 

두 개의 링크로 간주하십시오. 먼저이 페이지를로드하고 싶습니다.이 링크에는이 링크가 포함되어 있으며 해당 링크 중 하나를 클릭하십시오. 참고 [무작위로 변경된 URL을 클릭하면 URL이로드 될 것입니다.]

답변

3

cUrl이 반환 한 HTML을 구문 분석하고 링크를 찾은 다음 새 URL 요청을 통해 해당 URL을 가져와야합니다.

+0

당신은 –

3

이것은 오래된 게시물이지만 답변을 검색하는 모든 사용자에게 비슷한 문제가있어이를 해결할 수있었습니다. 나는 cUrl을 사용하여 PHP를 사용했다.

cUrl을 통한 링크를 따라 가기위한 코드는 매우 간단합니다.

// Create a user agent so websites don't block you 
$userAgent = 'Googlebot/2.1 (http://www.google.bot.com/bot.html)'; 

// Create the initial link you want. 
$target_url = "http://www.example.com/somepage"; 

// Initialize curl and following options 
$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); 


// Grab the html from the page 
$html = curl_exec($ch); 

// Error handling 
if(!$html){ 
    handle error if page was not reachable, etc 
    exit(); 
} 


// Create a new DOM Document to handle scraping 
$dom = new DOMDocument(); 
@$dom->loadHTML($html); 


// get your element, you can do this numerous ways like getting by tag, id or using a DOMXPath object 
// This example gets elements with id forward-link which might be a div or ul or li, etc 
// It then gets all the a tags (links) within all those divs, uls, etc 
// Then it takes the first link in the array of links and then grabs the href from the link 
$search = $dom->getElementById('forward-link'); 
$forwardlink = $search->getElementsByTagName('a'); 
$forwardlink = $forwardlink->item(0); 
$forwardlink = $getNamedItem('href'); 
$href = $forwardlink->textContent; 


// Now that you have the link you want to follow/click to 
// Set the target_url for the cUrl to the new url 
curl_setopt($ch, CURLOPT_URL, $target_url); 

$html = curl_exec($ch); 


// do what you want with your new link! 

이는 방식으로 수행 할 수있는 훌륭한 튜토리얼 : php curl tutorial

+0

은 브릴리언트 :)하십시오 예를 들어 나를 privide 수 있습니다! 고맙습니다. – adamj

관련 문제