/ / PHP Scraping with curl - Comment déboguer - php, curl, screen-scraping

PHP Scraping with curl - Comment puis-je déboguer - php, curl, screen-scraping

Je viens d’apprendre ce que la démolition et cURL est peuil y a quelques heures, et depuis lors, je joue avec ça. Néanmoins, je suis confronté à quelque chose d'étrange maintenant. Le code ci-dessous fonctionne très bien avec certains sites et pas avec d'autres (bien sûr, j'ai modifié l'URL et le xpath ...). Notez que je n'ai aucune erreur générée lorsque je teste si curl_exec a été exécuté correctement. Donc, le problème doit venir de quelque part après. Certaines de mes questions sont les suivantes:

  1. Comment puis-je vérifier si le nouveau DOMDocument a été créé correctement: if (??)
  2. Comment puis-je vérifier si le nouveau DOMDocument a été rempli correctement avec HTML?
  3. ... si un nouvel objet DOMXPath a été créé?

J'espère que j'ai été clair. Merci d'avance pour vos réponses. À votre santé. Marc

Mon php:

<?php
$target_url = "http://www.somesite.com";
$userAgent = "Googlebot/2.1 (http://www.googlebot.com/bot.html)";

// make the cURL request to $target_url
$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;
}

// parse the html into a DOMDocument
$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->query("somepath");

for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$url = $href->getAttribute("href");
echo "<br />Link: $url";
}

?>

Réponses:

2 pour la réponse № 1

Utilisez un try / catch pour vérifier si l'objet du documenta été créé, puis vérifiez la valeur de retour de loadHTML () pour déterminer si le code HTML a été chargé dans le document. Vous pouvez également utiliser un objet try / catch sur l'objet XPath.

try
{
$dom = new DOMDocument();

$loaded = $dom->loadHTML($html);

if($loaded)
{
// loaded OK
}
else
{
// could not load HTML
}
}
catch(Exception $e)
{
// document could not be created, see $e->getMessage()
}

0 pour la réponse № 2

Problème résolu. L'erreur est venue de firebug qui a donné un mauvais chemin. Un grand merci à MrCode pour son soutien ...