如何在 PHP 中回显抓取的 div?

问题描述 投票:0回答:1

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

foreach($anchors as $a) { 
    echo $a;
}
php web-scraping curl foreach
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();
}


?>
© www.soinside.com 2019 - 2024. All rights reserved.