无法选择链接

时间:2015-11-21 04:41:21

标签: php symfony web-scraping css-selectors domcrawler

我试图刮掉每个人的屁股。最后,我想点击链接并访问它链接的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();
    }

}

1 个答案:

答案 0 :(得分:0)

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

$crawler = new Crawler($html);

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

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

}