doulu5109 2019-06-05 18:27
浏览 210
已采纳

从特定表中提取链接

I have a html code with many html tables. I want to extract links from specific one which has specific div above.

Here's my sample code:

        <div class="boxuniwersal_header">Table 1</div>
        <img src="img/boxuniwersal_top.gif" width="210" height="18" alt="" style="margin-top: 5px" />
        <div class="boxuniwersal_content">
          <div class="boxuniwersal_subcontent">
            <div class='menu_m1'><table cellpadding="3"><tr><td><a href="http://link.com"><img src="some.jpg"  width="45" /></a></td><td><a href="http://link.com">Some text</a></td></tr></table></div>
            <br />
          </div>
        </div>
        <!-- /box  -->

        <!-- box  -->
        <div class="boxuniwersal_header">Table 2</div>
        <img src="img/boxuniwersal_top.gif" width="210" height="18" alt="" style="margin-top: 5px" />
        <div class="boxuniwersal_content">
          <div class="boxuniwersal_subcontent">
            <div class='menu_m1'><table cellpadding="3"><tr><td><a href="http://link2.com"><img src="some2.jpg"  width="45" /></a></td><td><a href="http://link2.com">Some text2</a></td></tr></table></div>
            <br />
          </div>
        </div>
$domXPath = new DOMXPath($domDocument);
$results = $domXPath->query("//div/div/table/tr/td/a|//table//tr/td//a"); //querying domdocument
foreach($results as $result)
{
    $links[]=$result->getAttribute("href");
}

This code returns all links. I want to grab only links from Table1. Is it possible?

  • 写回答

1条回答 默认 最新

  • douying6206 2019-06-05 18:59
    关注

    Your main problem is just tuning the XPath expression to select the right XML.

    If you change your XPath to

    //div[text()="Table 1"]/following-sibling::div[1]//table//a
    

    What this does is first find the <div> element whose text is the one your after.

    The following-sibling::div[1] part will look at the first <div> element at the same level as the <div> element already selected (this is the one where the <table> is).

    The last part just looks for all <a> elements within the enclosing <table>.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器