在Ruby中刮掉锚点的href值

问题描述 投票:0回答:1

在这个项目上工作,我必须抓一个“网站”,这只是一个本地文件夹中的一个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>

谢谢你的帮助!

ruby nokogiri screen-scraping scrape
1个回答
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"] }
© www.soinside.com 2019 - 2024. All rights reserved.