2017-02-19 31 views
1

我寫了一個小腳本來從Github中提取用戶名。我能拿到第一的用戶名的詳細信息,但我不明白我怎麼可以通過相同的CSS選擇器類元素的列表迭代把用戶名列表一起:如何遍歷li標籤並通過Nokogiri收集它們的值

page = agent.get('https://github.com/angular/angular/stargazers') 

html_results = Nokogiri::HTML(page.body) 

first_username = html_results.at_css('.follow-list-name').text 

first_username_location = html_results.at_css('.follow-list-info').text 

你能幫助我瞭解如何遍歷page.body中的所有follow-list-...元素並將值存儲在某個數組中?

回答

1

Nokogiri at_css返回一個(第一次)匹配。使用css反而得到匹配結果的陣列

require 'nokogiri' 
require 'open-uri' 
require 'pp' 

html = Nokogiri::HTML(open('https://github.com/angular/angular/stargazers').read) 

usernames = html.css('.follow-list-name').map(&:text) 
locations = html.css('.follow-list-info').map(&:text) 

pp usernames 
pp locations 

輸出:

["Jeff Arese Vilar", 
"Yaroslav Dusaniuk", 
"Matthieu Le brazidec", 
    ... ] 

[" @Wallapop ", 
" Ukraine, Vinnytsia", 
" Joined on Jul 4, 2014", 
... ] 

只是注意,解析您將需要處理分頁成員的其餘部分。即從所有其他頁面獲取數據:

http://github.com/.../stargazers?page=NN 

...其中NN是頁碼。

使用Github的API

一個更可靠的方法是使用Github的觀星列表API: https://developer.github.com/v3/activity/starring/#list-stargazers

+0

謝謝卡斯帕,大加讚賞。 – jbk

+0

說得更準確一點,'at _...'返回一個Node,'css','xpath'或'search'返回一個NodeSet。一個NodeSet的行爲很像一個節點陣列。 –