0

我正在尝试解析如下所示的 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 数组。

4

1 回答 1

2

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

于 2012-07-22T18:10:01.653 回答