0
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 将是一个条件 - 即如果存在跨度,则输入该级别,然后输入链接。

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

在此先感谢,非常感谢任何帮助!

谢恩

4

1 回答 1

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)"]
于 2013-11-07T13:05:13.660 回答