2010-07-30 29 views
5

, trong một trang web có nhiều liên kết được cung cấp.cách nhấp vào liên kết bằng cách sử dụng cURL.? Ví dụ:

forward backward 

xem hai liên kết này là hai liên kết. tôi muốn lần đầu tiên tải trang này, có chứa các liên kết này và nhấp vào bất kỳ liên kết nào trong số đó. LƯU Ý [Tôi không biết URL sẽ tải sau khi tôi nhấp vào nó khi nó thay đổi ngẫu nhiên]

Trả lời

3

Bạn sẽ phải phân tích cú pháp HTML mà cUrl đã trả về và tìm liên kết, sau đó kéo chúng qua yêu cầu cUrl mới.

+0

bạn có thể privide tôi với một ví dụ xin vui lòng :) –

3

Đây là một bài đăng cũ nhưng đối với bất kỳ ai tìm kiếm câu trả lời, tôi đã gặp phải sự cố tương tự và có thể giải quyết vấn đề đó. Tôi đã sử dụng PHP với cUrl.

Mã để theo liên kết thông qua cUrl rất đơn giản.

// 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! 

Đây là một hướng dẫn tuyệt vời để làm theo bằng cách này: php curl tutorial

+0

Brilliant! Cảm ơn bạn. – adamj

Các vấn đề liên quan