我正在尝试传递html以便找到标题和链接。现在,当我真的想一个接一个地循环浏览时,我可以同时获得所有的标题。我也无法获得链接,方法link();当我硬编码链接的实际名称时,方法返回错误
Current URI must be an absolute URL ("").
我需要一个foreach循环并获得标题和链接的东西,代码在下面,请帮助我完成
$html <<<<ol>
<li
class="first-child ol1">
<a href="http://link1"
class="story">
<span class="livestats-icon livestats-1">1:</span> Skywatchers await solar eclipse</a>
</li>
<li
class="ol2">
<a
href="http://link2"
class="story">
<span
class="livestats-icon livestats-2">2: </span>Indians caught 'cheating' in exams</a>
</li>
<li
class="ol3">
<a
href="http://link3"
class="story">
<span
class="livestats-icon livestats-3">3: </span>Hunting for Prince's vault</a>
</li>
</ol>>>>html
$crawler = new Crawler($html);
$message = $crawler->filterXPath('//ol')->text();
print_r($message);
$link = $crawler->selectLink('1: Skywatchers await solar eclipse')->link();
print_r($link);
您可以使用过滤器并使用css选择器选择链接,如:
$links = $crawler->filter('a')->links();
这将选择你拥有的所有a标签,如果你想要特定的标签,你需要一种方法来选择它们,如果你没有,然后在你需要选择的标签中添加一个css类:
$links = $crawler->filter('.myclass')->links());
它将返回链接数组。
编辑:
True刚刚尝试了你的代码,你需要一个URI,正如错误所说。。。我以为它在其他地方失败了,但它在爬行器结构中失败了。。。
$crawler = new Crawler($html, 'http'); //http is not a valid uri obviously but it does the trick if you dont need the uri.
您收到的错误实际上是从Symfony''DomCrawler''Link构造函数中抛出的InvalidArgumentException。这意味着您提供给selectLink()方法的值不是API中的有效名称:
为可单击的图像按名称或alt值选择链接。
DomCrawler确实有links()方法,根据API文档,该方法将:
返回列表中节点的链接对象数组。