【问题标题】:Extract html with xpath and php使用 xpath 和 php 提取 html
【发布时间】:2020-03-05 13:40:48
【问题描述】:

我似乎无法找到如何使用 xpath 获取 html 页面的值。我正在尝试检索页面上每个产品的图像源、价格和名称...我可以检索产品的数量,但之后不知何故无法获得任何值...我绝对不是一个专业人士,可以解释一下;)

我尝试了一些东西。我可以在 Chrome 中看到 xpath 并尝试使用它们,但它总是空的。在这一点上,我不知道该尝试什么。

<div class="prod-main">
    <div class="prod-thumb text-center" data-id="1948348">
        <div class="prod-thumb-16-9">
        <a href="#"><img class="lazy" alt="" src="image.jpg"></a>
        </div>
    </div>
    <div class="prod-info">
        <span class="prod-price">$8.00</span>
        <span class="prod-title"><a href="#">Product Name</a></span>
    </div>
</div>    
function url_get_contents ($Url) {
    if (!function_exists('curl_init')){ 
        die('CURL is not installed!');
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

    $newDom = new domDocument;
    $html=url_get_contents('test.html');
    $newDom->loadHTML($html);
    $newDom->preserveWhiteSpace = false;
    $finder = new DomXPath($newDom);

 $products = $finder->query('//div[@class="prod-main"]');

    foreach($products as $product) {
        $img = $finder->query('/div[2]/div/a/img/@src', $clip)[0]->value;
    }

phparray(24) { [0]=&gt; NULL [1]=&gt; NULL [2]=&gt; NULL [3]=&gt; NULL [4]=&gt; NULL [5]=&gt; NULL [6]=&gt; NULL [7]=&gt; NULL [8]=&gt; NULL [9]=&gt; NULL [10]=&gt; NULL [11]=&gt; NULL [12]=&gt; NULL [13]=&gt; NULL [14]=&gt; NULL [15]=&gt; NULL [16]=&gt; NULL [17]=&gt; NULL [18]=&gt; NULL [19]=&gt; NULL [20]=&gt; NULL [21]=&gt; NULL [22]=&gt; NULL [23]=&gt; NULL }

【问题讨论】:

    标签: php html xpath goutte


    【解决方案1】:

    好的,我正在使用 Goutter 到达那里。

    require 'vendor/autoload.php';
    use Goutte\Client;
    $url = "test.html";
    $client = new Client();
    $crawler = $client->request('GET', $url);
    $title_array = array();
    $titles=$crawler->filter('.prod-title')->each(function ($node){
        $title = $node->text();
        $title_array[]=$title;
        print_r($title_array);
    });    
    return $title_array;
    

    现在的问题是 print_r($title_array) 返回值但 $title_array 始终为空,我不明白为什么:/

    【讨论】:

      猜你喜欢
      • 2013-04-05
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      • 2011-06-03
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      相关资源
      最近更新 更多