php - 使用 if 语句通过 Xpath 获取数据
问题描述
我有三个 URL,这些 URL 包含我想要的数据。但是每个数据中的html标签不同。所以这就是为什么我不能为所有人提供相同的 Xpath。我需要尝试“如果在这个 Xpath 中找不到它,那么试试这个。” 像一种方式。但我对如何做到这一点有点困惑?
例如,这些是链接$linkBox
:
array(3) {
[0]=>
string(34) "https://lions-mansion.jp/MF161026/"
[1]=>
string(34) "https://lions-mansion.jp/MF171045/"
[2]=>
string(34) "https://lions-mansion.jp/MF171010/"
}
我将一一进入这些链接。而对于第一个。我给 Xpath:
$get = [];
foreach ($linkBox as $box){
$content = pageContent($box);
$Pars = new \DOMXPath($content);
$Route = $Pars->query("//ul[@id='snav']/li/a");
foreach ($Route as $Rot){
$get = $Rot->getAttribute('href');
}
}
但是 Xpath 不适合第二个或第三个。因此,如果使用 if 语句,如果它为空,我该如何编写试试这个?像代码?我能做到吗?还是我需要使用其他方式?
第二个 Box 的 Xpath 是:
$Route = $Pars->query("//nav[@id='siteActionNav']ul/li/a");
第二个 Box 的 Xpath 是:
$Route = $Pars->query("//ul[@id='subNavi']/li[2]/a");
解决方案
您可以做的是尝试每个 XPath 表达式并查看它是否返回任何元素。
例如,这是一个依次测试每个表达式的函数,DOMNodeList
如果找到任何匹配项则返回 a,否则抛出异常......
function findLinks(\DOMXPath $xp) {
$queries = [
'//ul[@id="snav"]/li/a',
'//nav[@id="siteActionNav"]ul/li/a',
'//ul[@id="subNavi"]/li[2]/a'
];
foreach ($queries as $query) {
$links = $xp->query($query);
if ($links->length > 0) {
return $links; // exits the function and returns the list
}
}
throw new \RuntimeException('No links found');
}
然后你可以像这样使用它
foreach ($linkBox as $box){
$content = pageContent($box);
try {
$links = findLinks(new \DOMXPath($content));
foreach ($links as $link){
$get[] = $link->getAttribute('href'); // note: changed to a push
}
} catch (\Exception $e) {
echo "Problem with $box: " . $e->getMessage();
}
}
推荐阅读
- python - 如何在 Python 中将 [String, String] 类型的 RDD 转换为 [Int,Int] 类型的 RDD?
- c# - 如何将 linq 的结果返回到 DataTable?
- python - 使用 Pandas DataFrame 按字段获取年龄分布百分比
- php - 无法提交成功的查询以在 PHP 中创建数据库条目
- gradle - 如果至少有一个不是最新的,Gradle 会复制所有文件
- python - 使用 python 的 prompt_toolkit 显示输出流
- javascript - UglifyJS 意外标记:关键字«const» - Webpack 4 Babel 7
- kubernetes - 了解 Kubernetes 的配置文件
- c# - c# DateTimeFormatInfo.ShortDatePattern 不对应“d”预定义格式
- javascript - 在 PDFNet Webviewer 的 leftPanel 中激活特定面板