【问题标题】:Get multiple value from html with dom (without id or classes)使用 dom 从 html 获取多个值(没有 id 或类)
【发布时间】:2018-08-18 05:39:10
【问题描述】:

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

这是该页面的表格结构示例,其中仅包含一个 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>

我能够废弃代理地址,但我在使用端口时遇到了困难,因为 &lt;td&gt; 没有 id 或类,并且作为值,有些具有超链接,而另一些则没有。

我怎样才能使整个报废结果的结果类似于 --> 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>';

请帮忙,
谢谢

【问题讨论】:

  • 使用DomNode-&gt;next_sibling 获取下一个tdstrip_tags 去除&lt;a&gt; 标签。
  • 这看起来不像 DOM,而是一个名为 SimpleHTMLDOM的 PHP 库

标签: php html parsing simple-html-dom


【解决方案1】:

与其为td 元素(或其中的元素,如abbra)编写选择器,不如为它们的tr 父元素编写选择器,然后循环遍历这些trs(行)和对于每一行,获取您需要的那一行的子代:

// 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的第一个和第二个孩子来提取数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-23
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多