gpt4 book ai didi

javascript - 使用 DOM 从第二个 HTML 表中提取数据,忽略第一个表

转载 作者:行者123 更新时间:2023-11-28 06:42:48 25 4
gpt4 key购买 nike

我有下面的 PHP 脚本,它通过命令提示符运行,如果页面上只有一个表,它可以正常工作,但如果页面上有两个表,它只会尝试拉出第一个表,是在某些情况下我可以说忽略第一个表并仅处理第二个表吗?

我无法控制 HTML,因此无法使用 ID 来定位表格。

HTML

<html>
</head>
...
</head>
<body>
<table>
<tr>
<th>Problem Table</th>
</tr>
<tr>
<td>Annoying table in the way!</td>
</tr>
</table>
<hr/>
<table>
<tr>
<th>ID</th>
<th>Asset</th>
</tr>
<tr>
<td>34234234</td>
<td>Website3</td>
</tr>
<tr>
<td>34234234</td>
<td>Website4</td>
</tr>
</table>
</body>
</html>

PHP

$dom = new DOMDocument();
$html = $dom->loadHTMLFile($url);

$dom->preserveWhiteSpace = false;

$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(0)->getElementsByTagName('tr');
$cols = $rows->item(0)->getElementsByTagName('th');
$row_headers = null;

foreach($cols AS $node) {
$row_headers[] = $node->nodeValue;
}

$table = array();
$rows = $tables->item(0)->getElementsByTagName('tr');
foreach($rows AS $row) {
$cols = $row->getElementsByTagName('td');
$row = array();
$i = 0;
foreach($cols AS $node) {
if ($row_headers != null) {
$row[$row_headers[$i]] = $node->nodeValue;
}
$i++;
}
if (!empty($row)) {
$table[] = $row;
}
}

最佳答案

我同意 @GCC404 的观点,即您应该使用 ID 或类更好地定位您的元素,因为这很容易导致错误。

但是,如果您特别想定位最后一个表,则只需将 0 替换为找到的项目数减 1:

$rows = $tables->item( $tables->length - 1 )->getElementsByTagName('tr');
// etc.

关于javascript - 使用 DOM 从第二个 HTML 表中提取数据,忽略第一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33649788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com