0

如何回显和抓取 div 类?我试过这个,但它不起作用。我正在使用 cURL 建立连接。我该如何回应它?我想要它在实际页面上的样子。$document = new DOMDocument(); $document->loadHTML($html); $selector = new DOMXPath($document); $anchors = $selector->query("/html/body//div[@class='resultitem']"); //你要检索的URL

foreach($anchors as $a) { 
    echo $a;
}
4

1 回答 1

3

邻居,我刚刚在下面制作了这个片段,它使用了您的逻辑,并进行了一些调整以在 get_contents 函数中显示网页中的指定类。也许您可以插入您的价值观并尝试一下?

(注意:我将错误检查放在那里以查看一些错误。在您调整时使用它会有所帮助。)

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

$url = "http://www.tizag.com/cssT/cssid.php";
$class_to_scrape="display";

$html = file_get_contents($url);
$document = new DOMDocument(); 
$document->loadHTML($html); 
$selector = new DOMXPath($document); 

$anchors = $selector->query("/html/body//div[@class='". $class_to_scrape ."']");

echo "ok, no php syntax errors. <br>Lets see what we scraped.<br>";

foreach ($anchors as $node) {
    $full_content = innerHTML($node);
   echo "<br>".$full_content."<br>" ;
}

/* this function preserves the inner content of the scraped element. 
** http://stackoverflow.com/questions/5349310/how-to-scrape-web-page-data-without-losing-tags
** So be sure to go and give that post an uptick too:)
**/
function innerHTML(DOMNode $node)
{
  $doc = new DOMDocument();
  foreach ($node->childNodes as $child) {
    $doc->appendChild($doc->importNode($child, true));
  }
  return $doc->saveHTML();
}


?>
于 2013-04-18T02:49:57.000 回答