【问题标题】:How to get the value of the href attribute?如何获取 href 属性的值?
【发布时间】:2011-06-11 11:11:22
【问题描述】:

在XPath的帮助下,在以下情况下如何获取href属性的值(只抓取正确的url)?:

<a href="http://foo.com">a wrong one</a>
<a href="http://example.com">the right one</a>
<a href="http://boo.com">a wrong one</a>

也就是说,如果链接有特定的文本,则获取 href 属性的值。

【问题讨论】:

    标签: php xpath


    【解决方案1】:

    这将选择属性:

    "//a[text()='the right one']/@href"
    

    【讨论】:

    • +1 不错,我不知道 DOMXPath 可以返回 DOMAttr 对象。 :)
    【解决方案2】:

    我认为这是最好的解决方案,您可以将它们中的每一个用作数组元素

    $String=    '
    <a href="http://foo.com">a wrong one</a>
    <a href="http://example.com">the right one</a>
    <a href="http://boo.com">a wrong one</a>
                ';
    
    $array=get_all_string_between($String,'href="','">');
    print_r($array);//just to see what is inside the array
    
    //now get each of them
    foreach($array as $value){
    echo $value.'<br>';
    }
    
    function get_all_string_between($string, $start, $end)
    {
        $result = array();
        $string = " ".$string;
        $offset = 0;
        while(true)
        {
            $ini = strpos($string,$start,$offset);
            if ($ini == 0)
                break;
            $ini += strlen($start);
            $len = strpos($string,$end,$ini) - $ini;
            $result[] = substr($string,$ini,$len);
            $offset = $ini+$len;
        }
        return $result;
    }
    

    【讨论】:

    • 真的吗?之间的字符串?不如使用 RegExp 解析有用?
    【解决方案3】:
    "//a[@href='http://example.com']"
    

    【讨论】:

      【解决方案4】:

      我会使用像 simple_html_dom.php 这样的开源类

      $oHtml = new simple_html_dom();
      $oHtml->load($sBody)
      foreach($oHtml->find('a') as $oElement) {
          echo $oElement->href
      }
      

      【讨论】:

      • 问题不是以“在XPath的帮助下”开头吗?
      【解决方案5】:

      这是一个使用 SimpleXML 的完整示例:

      $xml = '<html><a href="http://foo.com">a wrong one</a>'
              . '<a href="http://example.com">the right one</a>'
              . '<a href="http://boo.com">a wrong one</a></html>';
      $tree = simplexml_load_string($xml);
      $nodes = $tree->xpath('//a[text()="the right one"]');
      $href = (string) $nodes[0]['href'];
      

      【讨论】:

      • 使用 [.="the right one"] 优先于 [text()="the right one"]。因为它更短,并且值中可能有 cmets 会将其拆分为多个文本节点。
      • 但这会选择a 元素,而不是@href
      • XPath 查询为真。但请检查最后的作业。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      • 2021-11-08
      • 2016-06-07
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多