我正在为一个项目构建一个自定义刮刀。我现在可以抓取网页上的所有链接,存储HREF,并将文本锚定在数据库中。但是,当我试图确定锚元素是否包含图像元素时,我会陷入困境。
这是我的代码:
foreach($rows as $row) {
$url = $row['url'];
$dom = new DOMDocument;
libxml_use_internal_errors(TRUE); //disable libxml errors
$dom->loadHTML(file_get_contents($url));
// Write source page, destination URL and anchor text to the database
foreach($dom->getElementsByTagName('a') as $link) {
$href = $link->getAttribute('href');
$anchor = $link->nodeValue;
$img = $link->getElementsByTagName('img');
$imgalt = $img->getAttribute('alt');
然后我将数据写入数据库。这在$ img和$ imgalt中工作正常,但我真的想确定锚是否包含图像以及是否有alt属性。我知道问题是我如何尝试使用getElementsByTagName选择图像。我一直在谷歌搜索并尝试了许多不同的建议,但似乎没有任何工作。这甚至可能吗?
我按照here提到的说明进行操作。
有一些进展。我可以回应锚元素中的图像的HTML(如果我只是echo
DOMinnerHTML($link)
),但我仍然无法获得alt属性。我不断得到“在一个非对象上调用成员函数getAttribute()
”。
这是我现在的代码:
foreach($dom->getElementsByTagName('a') as $link) {
$href = $link->getAttribute('href');
$anchor = $link->nodeValue;
$imgdom = DOMinnerHTML($link);
$imgalt = $imgdom->getAttribute('alt');
if(isset($imgalt)){
echo $imgalt;
}
好吧,我可以假设你想要这样的东西:
<?php
$html_fragment = <<<HTML
<html>
<head>
<title></title>
</head>
<body>
<div id="container">
<a href="#a">there is n image here</a>
<a href="#b"><img src="path/to/image-b" alt="b: alt content"></a>
<a href="#c"><img src="path-to-image-c"></a>
<a href="#d"><img src="path-to-image-d" alt="c: alt content"></a>
</div>
</body>
</html>
HTML;
$dom = new DOMDocument();
@$dom->loadHTML($html_fragment);
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
# link contains image child?
$imgs = $link->getElementsByTagName('img');
$has_img = $imgs->length > 0;
if ($has_img) {
$has_alt = (bool) $imgs->item(0)->getAttribute("alt");
# img element has alt attribute?
if ($has_alt) {
// do something...
}
} else {
// do something...
}
}
请记住,如PHP文档中所述,DOMElement::getAttribute()返回属性的值,如果找不到具有给定名称的属性,则返回空字符串。因此,为了检查节点属性是否存在,只需检查返回值是否为空字符串。