在Ruby中刮掉锚点的href值

时间:2017-12-20 13:04:40

标签: ruby nokogiri screen-scraping scrape

在这个项目上工作,我必须抓住一个"网站,"这只是一个本地文件夹中的html文件。无论如何,我一直试图缩减每个学生对象的锚标记的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

enter image description here

这是学生档案之一。它们都是一样的,所以我只想抓取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>

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

一旦你在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"] }