-3

我正在尝试抓取网站的链接文本,即 SCRAPE THIS。我想对页面上的所有链接执行此操作。到目前为止,我有这个:

<?php

$target_url = "SITE I WANT TO SCRAPE";

// make the cURL request to $target_url
$ch = curl_init();
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->evaluate("/html/body//a/text()");

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

我对这些东西很陌生,无法弄清楚我做错了什么?

谢谢!

4

2 回答 2

2

在您的 for 循环中,$href不是字符串。它实际上是一个 DOMText 节点。为了将其用作字符串,您需要访问其nodeValue属性。

for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    echo "<br />Link stored: $href->nodeValue";
}
于 2012-08-23T20:41:06.040 回答
1

尝试:

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

for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i)->textContent;
    echo "<br />Link stored: $href";
}
于 2012-08-23T20:43:12.263 回答