【问题标题】:Get the href value using XPath/Hpple/Objective-C使用 XPath/Hpple/Objective-C 获取 href 值
【发布时间】:2012-06-30 12:33:39
【问题描述】:

我尝试了所有对我有意义(和没有意义)的方法。我有以下 html 代码,我尝试在 Objective-C 中使用 XPath 进行解析:

<tr style="background-color: #eaeaea">
   <td class="content">
      <a href="index.php?cmd=search&id=foo">bar</a>
   </td>
</tr>

我通过//tr/td[@class='content']/a/text() 得到"bar"

但我不知道如何获得index.php?cmd=search&amp;id=foo

这真的让我绝望:-(

非常感谢您的帮助!

【问题讨论】:

    标签: html xpath href hpple


    【解决方案1】:

    在尝试了整个晚上(再次)之后,我发现了如何解决我的问题:

    //Put the elements in an array
    NSArray *someArray = [xpathParser searchWithXPathQuery:@"//tr/td[@class='content']/a"];
    
    //Just one possibility to make a for-loop
    for (TFHppleElement *element in someArray) {
        //This is the important line:
        NSString *myURL = [[element attributes] objectForKey:@"href"];
        //Do whatever you want with myURL
    }
    

    希望对大家有所帮助!

    【讨论】:

      【解决方案2】:

      要通过XPATH获取href部分,需要在属性名前使用@符号。

      //tr/td[@class='content']/a/@href
      

      更新:

      看来,你指的是iphone。

      尝试这样的方法来获取属性值

      NSArray *link = [xmlData valueForKey:@"href"];
      

      【讨论】:

      • 感谢您的快速回答,但我试过了,但它不起作用......我不知道,我将它找到的值存储在 NSArray 中,如果我使用“// tr/td[@class='content']/a/text()" 一切都很好,但是当我将其更改为 "//tr/td[@class='content']/a/@href" Xcode 说“ *** -[__NSArrayM insertObject:atIndex:]: object cannot be nil" 所以 XPath 没有找到任何东西,是吗?
      • 非常感谢您的帮助,又过了一个晚上,我找到了办法。如果有其他(更好的)方法,请告诉我!
      • 有 - 你能把你的答案标记为正确吗?我也发现 objectForKey:@"href" 是解决方案。
      猜你喜欢
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-03
      • 2021-11-08
      相关资源
      最近更新 更多