使用 dom 从 html 获取多个值(没有 id 或 类)

Get multiple value from html with dom (without id or classes)

我正在尝试从此 http://jsbin.com/noxuqusoga/edit?html 输出 html 页面获取代理和端口值。

这是该页面中 table 结构的示例,仅包括一个 tr,但实际 HTML 有许多具有相似结构的 tr 元素:

<table class="table" id="tbl_proxy_list" width="950">
    <tbody>
        <tr data-proxy-id="1355950">
            <td align="left"><abbr title="103.227.175.125">103.227.175.125 </abbr></td>
            <td align="left"><a href="/proxy-server-list/port-8080/" title="Port 8080 proxies">8080</a></td>
            <td align="left"><time class="icon icon-check timeago" datetime="2018-08-18 04:56:47Z">9 min ago</time></td>
            <td align="left">
            <div class="progress-bar" data-value="22" title="1089">
            <div class="progress-bar-inner" style="width:22%; background-color: hsl(26.4,100%,50%);">&nbsp;</div>
            </div>
            <small>1089 ms</small></td>
            <td style="text-align:center !important;"><span style="color:#009900;">95%</span> <span> (94)</span></td>
            <td align="left"><img alt="sg" class="flag flag-sg" src="/assets/images/blank.gif" style="vertical-align: middle;" /> <a href="/proxy-server-list/country-sg/" title="Proxies from Singapore">Singapore <span class="proxy-city"> - Bukit Timah </span> </a></td>
            <td align="left"><span class="proxy_transparent" style="font-weight:bold; font-size:10px;">Transparent</span></td>
            <td><span>-</span></td>
        </tr>
  </tbody>
</table>

我可以废弃代理地址,但我在使用端口时遇到困难,因为 <td> 没有 id 或 class 并且作为价值,有些有超链接,有些没有't.

如何使整个报废结果像 --> ip:port 这样的结果。

这是我的代码

$html = file_get_html('http://jsbin.com/noxuqusoga/');

// Find all images
foreach($html->find('abbr') as $element)
       echo $element->title . '<br>';

foreach($html->find('td a') as $element)
       echo $element->plaintext . '<br>';

请帮忙,
谢谢

与其为 td 元素(或其中的元素,如 abbra 编写选择器,不如为其编写选择器 tr parent,然后遍历这些 trs(行),对于每一行,得到你需要的那行的 children:

// Select all tr elements inside tbody
foreach ($html->find('tbody tr') as $row)
    // the second parameter (zero) indicates we only need the first element matching our selector

    // ip is in the first <abbr> element that is child of a td
    $ip = $row->find('td abbr', 0)->plaintext;
    // port is in the first <a> element that is child of a td
    $port = $row->find('td a', 0)->plaintext;
    print "$ip:$port\n";
}

作为替代方案,您应该知道在选择元素时,除了使用 css 选择器之外,您还可以选择通过索引获取元素。在你的情况下,你想要从每个 tr 中得到的是每个 tr 元素内的第一个和第二个 td 元素。所以也可以找到每个tr的第一个和第二个child来提取数据