在 Ruby 中抓取锚点的 href 值

Scraping the href value of anchor in Ruby

在这个项目中,我必须抓取一个 "website,",它只是一个本地文件夹中的一个 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>

感谢您的帮助!

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