如果存在与否,Nokogiri会获得元素

时间:2013-11-07 12:56:14

标签: ruby web-scraping nokogiri

Quite simply can you do a conditional scrape, i.e. I want an <a> 
tag within a parent, and if a <span> is contained within that parent
(so the span is holding the <a>, instead of the parent), I still want
to drill into the span regardless for the <a>

希望这个例子能够提供足够的细节。

<tr>
    <td>1989</td>
    <td>
      <i>
       <a href="/wiki/Always_(1989_film)" title="Always (1989 film)">Always</a>
     </i>
    </td>
     <td>Pete Sandich</td>
</tr>

我可以使用

访问<a>罚款

all_links = doca.search('//tr//td//i//a[@href]')

但我想知道的是我还可以添加一个条件,所以如果<a>周围有一个范围,可以将其放入搜索中吗?

 <tr>
    <td>1989</td>
    <td>
      <i>
       <span>
         <a href="/wiki/Always_(1989_film)" title="Always (1989 film)">Always</a>
       </span>
     </i>
    </td>
     <td>Pete Sandich</td>
</tr>

有没有办法有条件地抓住<a>,就像这样:

all_links = doca.search('//tr//td//i//?span//a[@href]')

其中?span是条件 - 即如果有跨度,则输入该级别,然后输入链接。

如果没有跨度,则跳过它,然后输入链接。

提前致谢,非常感谢任何帮助!

沙恩

1 个答案:

答案 0 :(得分:2)

我们走了:

require 'nokogiri'

doc = Nokogiri::HTML::Document.parse <<-eot
<tr>
    <td>1989</td>
    <td>
      <i>
       <span>
         <a href='/wiki2/Always_(1989_film)' title='Always (1989 film)'>Always</a>
       </span>
     </i>
    </td>
        <td>
      <i>
         <a href='/wiki1/Always_(1989_film)' title='Always (1989 film)'>Always</a>
     </i>
    </td>
     <td>Pete Sandich</td>
</tr>
eot

# xpath expression will grab a tag if it is wrapped inside the span tag
node = doc.xpath("//tr//i//a[name(./..)='span']")
p node.size # => 1
p node.map{ |n| n['href'] } # => ["/wiki2/Always_(1989_film)"]