【问题标题】:Scraping the href value of anchor in Ruby抓取 Ruby 中锚的 href 值
【发布时间】:2017-12-20 13:04:39
【问题描述】:

在这个项目上我必须抓取一个“网站”,这只是一个本地文件夹中的一个 html 文件。无论如何,我一直在尝试为每个 student 对象搜索锚标记的 href 值(一个 url)。我也在寻找其他的东西,所以忽略其余的。这是我目前所拥有的:

def self.scrape_index_page(index_url) #responsible for scraping the index page that lists all of the students
    #return an array of hashes in which each hash represents one student.
    html = index_url
    doc = Nokogiri::HTML(open(html))
    # doc.css(".student-name").first.text
    # doc.css(".student-location").first.text
    #student_card = doc.css(".student-card").first
    #student_card.css("a").text
end

这是其中一份学生资料。它们都是一样的,所以我只是对抓取 href url 值感兴趣。

<div class="student-card" id="eric-chu-card">
   <a href="students/eric-chu.html">
      <div class="view-profile-div">
         <h3 class="view-profile-text">View Profile</h3>
      </div>
      <div class="card-text-container">
         <h4 class="student-name">Eric Chu</h4>
         <p class="student-location">Glenelg, MD</p>
      </div>
   </a>
</div>

感谢您的帮助!

【问题讨论】:

  • 你的问题是什么?
  • 请分享url或html文档样本
  • 我正在尝试获取学生卡类容器的 href 值。

标签: ruby nokogiri screen-scraping scrape


【解决方案1】:

一旦你在 Nokogiri 中获得了一个锚标签,你就可以像这样获得 href:

anchor["href"]

因此,在您的示例中,您可以通过执行以下操作来获取 href:

student_card = doc.css(".student-card").first
href = student_card.css("a").first["href"]

如果你想一次收集所有的 href 值,你可以这样做:

hrefs = doc.css(".student-card a").map { |anchor| anchor["href"] }

【讨论】:

  • 唯一的事情,我收到一个关于 href 的错误:没有将 String 隐式转换为 Integer。想知道什么给了?
  • 很抱歉。当您使用css 方法时,它返回一个Nokogiri::XML::NodeSet。您想从 NodeSet 中的 Nokogiri::XML::Element 获取 href。在您的示例中,student_card.css("a").first["href"] 应该返回 href。
猜你喜欢
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-04
  • 1970-01-01
相关资源
最近更新 更多