php - 问:如何在不使用 XPath 的情况下从网页中查找部分
问题描述
我需要从网页中提取一个部分。我需要一个带有 DOM API 而没有 XPath 的版本。这是我的版本。需要从“Latest Distributions”中提取并在浏览器中显示信息。
<?php
$result = file_get_contents ('https://distrowatch.com/');
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($result);
$xpath = new DOMXPath($doc);
$node = $xpath->query('//table[@class="News"]')->item(0);
echo $node->textContent;
解决方案
这看起来很简单,但是这样做而不是 XPath 是浪费时间。
<?php
$result = file_get_contents ('https://distrowatch.com/');
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($result);
foreach ($doc->getElementsByTagName("table") as $table) {
if ($table->getAttribute("class") === "News") {
echo $table->textContent;
break;
}
}
推荐阅读
- excel - 运行时 1004:OnTime _Application 在打开 excel 文件时失败启用编辑
- gitlab - 是否可以在没有通配符证书的情况下在 Gitlab 中使用评论应用程序?
- node.js - 如果 tsConfig 目标为 ESNext、ES2021 或 ES2020,则 ts-jest 可选链接不起作用
- python-3.x - 如何在 python 代码中使用 google-cloud-os-config 类?
- powershell - 在本地 Windows 机器上使用 gitlab-runner 执行 powershell 脚本
- openpyxl - 如何仅将值而不是公式复制到另一个工作簿中?(openpyxl)
- php - 致命错误:未捕获错误:找不到类“zcrmsdk\crm\setup\restclient\ZCRMRestClient”
- java - 使用 Groovy 进行简单线性回归
- ios - 如何从 Swift 中的 deeplink 获取重定向 url
- django - Django生成PDF css错误并且渲染很慢