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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。