2015-11-21 77 views
0

我试图刮掉每个.row的href。最终,我想点击链接并访问它链接的DOM,但我无法获得Link对象或href属性。无法选择链接

不确定a属性是否有任何文本是一个问题,但这是我必须与之合作的DOM。

帮助?

<?php require 'vendor/autoload.php'; 

use Symfony\Component\DomCrawler\Crawler; 

$html = <<<'HTML' 
<!doctype html> 
<html> 
    <body> 
    <div class="content"> 
     <p class="row"><a href="/uri1"></a></p> 
     <p class="row"><a href="/uri2"></a></p> 
     <p class="row"><a href="/uri3"></a></p> 
    </div> 
    </body> 
<html> 
HTML; 

$dom = new Crawler($html); 

$content = $dom->filter('.row'); 
$rows = []; 

foreach ($content as $element) 
{ 
    $node = new Crawler($element); 
    $link = $node->filter('a'); 
    echo $link->html(); // Empty? 

    try 
    { 
     $link = $node->selectLink('')->link(); 
     echo $link->getUri(); 
    } 
    catch (Exception $ex) 
    { 
     // Throws: Current URI must be an absolute URL ("").Current URI must be 
     // an absolute URL ("").Current URI must be an absolute URL (""). 
     echo $ex->getMessage(); 
    } 

} 

回答

0

我使用xpath来使用DomCrawler来进行DOM元素的填充,因为我喜欢这样我可以更好地控制我正在过滤的内容。下面的代码应该在你的html中回显urls。

$crawler = new Crawler($html); 

$crawler->filterXPath("//p[@class='row']")->each(function (Crawler $node, $i) { 

$url = $node->filterXPath("//a/@href")->text(); 
echo $url; 

}