我正在尝试抓取 a website使用 DOMXPath 查询方法。我已成功从此页面抓取了每个新闻主播的 20 个个人资料 URL。
$url = "http://www.sandiego6.com/about-us/meet-our-team";
$xPath = "//p[@class='bio']/a/@href";
$html = new DOMDocument();
@$html->loadHtmlFile($url);
$xpath = new DOMXPath( $html );
$nodelist = $xpath->query($xPath);
$profileurl = array();
foreach ($nodelist as $n){
$value = $n->nodeValue;
$profileurl[] = $value;
}
我使用生成的数组作为 URL 从每个新闻主播的个人简介页面中抓取数据。
$imgurl = array();
for($z=0;$z<$elementCount;$z++){
$html = new DOMDocument();
@$html->loadHtmlFile($profileurl[$z]);
$xpath = new DOMXPath($html);
$nodelist = $xpath->query("//img[@class='photo fn']/@src");
foreach($nodelist as $n){
$value = $n->nodeValue;
$imgurl[] = $value;
}
}
每个新闻主播个人资料页面都有 6 个我需要抓取的 xPath($imgurl 数组就是其中之一)。然后我将这些抓取的数据发送到 MySQL。
到目前为止,一切都运行良好 - 除了当我尝试从每个个人资料中获取 Twitter URL 时,因为并非在每个新闻主播个人资料页面上都找到此元素。这导致 MySQL 接收 5 列(20 个完整行)和 1 列(twitterurl)(18 行数据)。这 18 行没有与其他数据正确对齐,因为如果 xPath 不存在,它似乎会被跳过。
如何解决缺失的 xPath?在寻找答案时,我发现有人这样说:“nodeValue 永远不能为 null,因为没有值,节点就不会存在。”考虑到这一点,如果没有 nodeValue,我如何以编程方式识别这些 xPath 何时不存在,并在循环到下一个迭代之前用其他默认值填充该迭代?
以下是 Twitter URL 的查询:
$twitterurl = array();
for($z=0;$z<$elementCount;$z++){
$html = new DOMDocument();
@$html->loadHtmlFile($profileurl[$z]);
$xpath = new DOMXPath($html);
$nodelist = $xpath->query("//*[@id='bio']/div[2]/p[3]/a/@href");
foreach($nodelist as $n){
$value = $n->nodeValue;
$twitterurl[] = $value;
}
}
最佳答案
由于 twitter 节点出现零次或一次,因此将 foreach 更改为
$twitterurl [] = $nodelist->length ? $nodelist->item(0)->nodeValue : NULL;
这将使内容保持同步。但是,您必须在用于将 NULL 值插入数据库的查询中做出安排来处理 NULL 值。
关于php - 使用 DOMXPath 查询方法抓取网站时,如何解释丢失的 xPath 并保持数据统一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26367786/