4

(希望这不是违反礼仪:我在 RailsForum 上发布了这篇文章,但最近我没有得到太多回应。)

有没有其他人遇到过 Mechanize 无法通过 CSS 选择器识别锚标签的问题?

HTML 看起来像这样(为清楚起见,删除了空格的片段):

<td class='calendarCell' align='left'>
<a href="http://www.mysite.org/index.php/site/ActivitiesCalendar/2010/02/10/">10</a>
<p style="margin-bottom:15px; line-height:14px; text-align:left;">
<span class="sidenavHeadType">
 Current Events</span><br />
<b><a href="http://www.mysite.org/index.php/site/
Clubs/banks_and_the_fed" class="a2">Banks and the Fed</a></b>
<br />
10:30am- 11:45am
</p>

我正在尝试从这些事件中收集数据。除了在<p>. 里面显然有一个<a>标签<b>,我将需要点击该链接以获取有关此事件的更多详细信息。

在我的 rake 任务中,我有:

agent.page.search(".calendarCell,.calendarToday").each do |item|
  day = item.at("a").text

  item.search("p").each do |e|
    anchor   = e.at("a")
    puts anchor
    puts e.inner_html

  end
end

有趣的是 item.at("a") 总是返回锚点。但是 e.at("a") 返回 nil。当我对 p 元素执行 inner_html 时,它完全忽略了锚点。示例输出:

nil

<span class="sidenavHeadType">
 Photo Club</span><br><b>Indexing Slide Collections</b>
<br>
2:00pm- 3:00pm

但是,当我直接使用 Nokogiri 运行相同的抓取时:

doc.css(".calendarCell,.calendarToday").each do |item|
  day = item.at_css("a").text
  item.css("p").each do |e|
    link     = e.at_css("a")[:href]
    puts e.inner_html
  end
end

它识别内部

,它会返回href等。

<span class="sidenavHeadType">
 Bridge Party</span><br><b><a href="http://www.mysite.org/index.php/site/Clubs/party_bridge_51209" class="a2">Party Bridge</a></b>
<br>
7:00pm- 9:00pm

Mechanize 应该使用 Nokogiri,所以我想知道我的版本是否不好,或者这是否也会影响其他人。

感谢任何线索。

4

1 回答 1

1

没关系。虚惊。在我的 Nokogiri 任务中,我指向包含锚点的页面的本地副本。实时页面需要登录,所以当我浏览它时,我可以看到 a 标签。将登录添加到 rake 任务解决了它。

于 2010-02-10T02:04:31.167 回答