【问题标题】:Xpath and Nokogiri: why can't I get this attribute?Xpath 和 Nokogiri:为什么我不能得到这个属性?
【发布时间】:2012-07-22 18:06:58
【问题描述】:

我正在尝试解析如下所示的 HTML:

<p class="row">
            <span class="itemdate"> Jul 22</span>
            <span class="itemsep"> - </span> 
            <a href="http://newyork.craigslist.org/brk/abo/3102470187.html">$2000 / 3br - Three bedroom apartment/new renovtion</a>
            <span class="itemsep"> - </span>
            <span class="itempn"><font size="-1"> (Bushwick-L Train-Close to Williamsburg)</font></span>
            <span class="itempx"> <span class="p"> pic</span></span>
            <span class="itemcg" title="abo"> <small class="gc"><a href="/abo/">apts by owner</a></small></span>
        </p>

当我执行这个调用时:

page.xpath("//p[contains(@class, 'row')]/a").first

我得到如下结果:

#<Nokogiri::XML::Element:0x3feea2631444 name="a" 
attributes=[#<Nokogiri::XML::Attr:0x3feea2631390 name="href"
value="http://newyork.craigslist.org/brk/abo/3102470187.html">] 
children=[#<Nokogiri::XML::Text:0x3feea2630ad0 "$2000 / 3br - Three bedroom">]>

因此,通过查看 xpath 文档,我应该能够通过执行以下操作来返回 url:

page.xpath("//p[contains(@class, 'row')]/a@href").first 

但我收到此错误:

Nokogiri::XML::XPath::SyntaxError Exception: Invalid expression: 
//p[contains(@class, 'row')]/a@href

我知道如何从 Nokogiri 对象获取 URL,但我宁愿 xpath 搜索只返回一个 URL 数组。

【问题讨论】:

    标签: ruby-on-rails xpath nokogiri


    【解决方案1】:

    你少了一个斜线,你需要.../a/@href

    【讨论】:

      猜你喜欢
      • 2012-02-27
      • 2018-05-24
      • 2012-01-07
      • 2018-05-27
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多