【问题标题】:XPath Query: get attribute href from a tagXPath 查询:从标签中获取属性 href
【发布时间】:2014-01-30 11:34:30
【问题描述】:

我想使用 XPath 从 a 标记中获取 href 属性,但它在同一个文件中出现了两次。我怎么相处? 我需要检查是否有值为 $street/object 的 href 属性,我有此代码但它不起作用:

$product_photo     = $xpath->query("//a[contains(@href,'{$object_street}fotos/')][1]");
        $product_360       = $xpath->query("//a[contains(@href,'{$object_street}360-fotos/')][1]");
        $product_blueprint = $xpath->query("//a[contains(@href,'{$object_street}plattegrond/')][1]");
        $product_video     = $xpath->query("//a[contains(@href,'{$object_street}video/')][1]");

它根本不返回任何东西。谁能帮帮我?

【问题讨论】:

    标签: html xpath domdocument


    【解决方案1】:

    对于以下 HTML 文档:

    <html>
      <body>
        <a href="http://www.example.com">Example</a> 
        <a href="http://www.stackoverflow.com">SO</a> 
      </body>
    </html>
    

    xpath 查询 /html/body//a/@href(或简称为 //a/@href)将返回:

    http://www.example.com http://www.stackoverflow.com

    要选择特定实例,请使用/html/body//a[N]/@href

    $ /html/body//a[2]/@href http://www.stackoverflow.com

    要测试属性中包含的字符串并返回属性本身,请检查标记而不是属性:

    $ /html/body//a[包含(@href,'example')]/@href http://www.example.com

    将两者混合:

    $ /html/body//a[包含(@href,'com')][2]/@href http://www.stackoverflow.com

    【讨论】:

    • 编辑: 如何检查特定的 href 属性?然后我应该使用/html/body//a[1]/@href='{$object_street}/x'吗?
    • 非常感谢您的努力!不幸的是,我仍然遇到麻烦,我想这不是查询错误。你介意看一下我的程序代码并让我走上正轨吗?因为,如果是这样,我会发布代码。
    • 确保您的查询正确评估 {$object_street},可能首先将其放入字符串中,如 "string s = //a[contains(@href,'{$object_street}fotos/ ')][1]/@href" 并检查 s 是否正常。
    • 我已将我的问题放在这里,但没有人回应。所以也许你可以看看它,好吗?
    • 它返回的是一个数组而不是特定的字符串值
    【解决方案2】:

    @mockinterface 分享的答案是正确的。虽然我想加我的 2 美分。

    如果有人使用像 scrapy 这样的框架,你将不得不像这样使用 /html/body//a[contains(@href,'com')][2]/@href 和 get():

    response.xpath('//a[contains(@href,'com')][2]/@href').get()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      • 2011-07-09
      • 2014-07-05
      相关资源
      最近更新 更多