2017-12-20 21 views
0

로컬 폴더 중 하나에있는 html 파일 인 "웹 사이트"를 다듬어야하는이 프로젝트에서 작업합니다. 어쨌든, 나는 각 학생 객체에 대한 앵커 태그의 href 값 (URL)으로 긁어 내려고 노력했습니다. 나는 또한 다른 일을 위해 긁어 모으고 있으므로 나머지는 무시하십시오. 여기에 지금까지 무엇을 가지고 : 여기Ruby에서 앵커의 href 값을 긁음

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> 

감사합니다.

+0

무엇이 질문입니까? –

+0

'url' 또는 html 문서 샘플을 공유하십시오. – Abdullah

+0

학생 카드 클래스 컨테이너의 href 값을 가져 오려고합니다. – alexnewby

답변

2

당신이 노코 기리에서 앵커 태그를 일단,이 같은 href를 얻을 수 있습니다 :

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

: 귀하의 예제에서 그래서

anchor["href"] 

, 당신은 다음을 수행하여 HREF를 얻을 수 한 번에 모든 href 값을 수집하려면 다음과 같이 할 수 있습니다.

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

고마워요! 도움이됩니다! – alexnewby

+0

유일한 것은, href에 대한 오류가 발생했습니다 : Integer로 String을 암시 적으로 변환하지 않았습니다. 원더 무엇이 제공합니까? – alexnewby

+0

죄송합니다. 'css' 메서드를 사용하면'Nokogiri :: XML :: NodeSet'을 반환합니다. NodeSet 내부의'Nokogiri :: XML :: Element'에서 href를 얻고 싶습니다. 귀하의 예제에서, 'student_card.css ("a"). first [ "href"]'는 href를 반환해야합니다. –