【问题标题】:Ruby ,Mechanize. How to get specific <a> tag text红宝石,机械化。如何获取特定的 <a> 标签文本
【发布时间】:2014-07-19 04:47:04
【问题描述】:

我的目标是获得“我想要这个文本”文本。

<div class="class1">
<b>xxxxx</b>
<a href="http://example.com/want/xxxx">I want this text</a>
<a href="http://example.com/want/yyyy">I want this text</a>
<b>yyyyy</b>
<a href="http://example.com/unnece/xxxx">no need</a>
<a href="http://example.com/unnece/xxxx">no need</a>
</div>

<div class="class2">
<a href="http://example.com/want/xxxx">no need</a>
<a href="http://example.com/want/yyyy">no need</a>
</div>

我尝试编写代码。

test = agent.page.search("div[@class='class1'] / a").text

但是,我也得到了“不需要”的文字

我该怎么做?我正在使用宝石:

require 'mechanize'
require 'open-uri'

如果可能的话,我想在文本之间放置逗号...

【问题讨论】:

  • 您可以尝试使用 gem 'nokogiri',它有 css 选择器和查找许多元素的方法
  • @Pavel - Mechanize 是 Nokogiri 的姊妹项目,并将其作为解析器包含在内

标签: ruby-on-rails ruby web-scraping mechanize


【解决方案1】:

可能有很多方法,但最明显的是:

agent.page.search('.class1 a[href*=want]').text

【讨论】:

  • @pguardiario 获取href怎么样?,谢谢
  • @stan 只需将 .text 替换为 [:href]
【解决方案2】:

我将使用这样的 css 选择器:

test = agent.page.search("div.class1 > a:first-of-type").text

【讨论】:

  • 这只是第一个a,他想要前2个a
猜你喜欢
  • 2012-09-01
  • 2012-04-28
  • 2011-01-10
  • 2015-07-27
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 2011-01-12
  • 2017-06-24
相关资源
最近更新 更多