douliang2087 2013-04-17 08:11
浏览 49
已采纳

带有DOMDocument的DomXPath获取<img>类URL

I am writing a little scraper script that will find the image URL that has a particular class name. I know that my cURL and DOMDocument is functioning okay, and even the DomXPath really (as far as I can tell, there are no errors) But I am struggling to work out how to get the URL of the xpath query results.

My code so far:

$dom = new DOMDocument();
@$dom->loadHTML($x);

$xpath = new DomXpath($dom);
$div = $xpath->query('//*[@class="productImage"]');


var_dump($div);
echo $div->item(0);

If I var_dump($x) the page outputs no problem. So the CURL is working fine. But I do not know how to get the data that is contained in the $div. I am trying to find an Image with a class of 'productImage' which looks like:

<img src="/uploads/5W/yP/5WyPP4l7Z-jmZRzu_MJ6zg/1077-d.jpg" border="1" alt="Album" class="productImage">

I want the source of that image tag.

Any suggestions?

  • 写回答

2条回答 默认 最新

  • dongritan5654 2013-04-17 08:15
    关注
    $dom = new DOMDocument();
    $dom->loadHTML($x);
    
    $xpath = new DomXpath($dom);
    $imgs  = $xpath->query('//*[@class="productImage"]');
    
    foreach($imgs as $img)
    {
        echo 'ImgSrc: ' . $img->getAttribute('src') .'<br />' . PHP_EOL;
    }
    

    Try that...

    == EDIT: Additional Info ==

    The reason I use a loop here is because you may find more than one img. If you know there is only one element (or you want the first dom node found) you can access the elelement from the domnodelist via the item method of domnodelist - like so:

    $dom = new DOMDocument();
    $dom->loadHTML($x);
    
    $xpath = new DomXpath($dom);
    $img   = $xpath->query('//*[@class="productImage"]');
    
    echo 'ImgSrc: ' . $img->item(0)->getAttribute('src') .'<br />' . PHP_EOL;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?