如何使用Nokogiri遍历li标签并收集它们的值
How to traverse li tags and collect their values with Nokogiri
我写了一个小脚本来从 Github 中提取用户名。我可以获取第一个用户名的详细信息,但我不明白如何使用相同的 CSS 选择器 class 遍历元素列表以将用户名列表放在一起:
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-...
元素并将值存储在某个数组中吗?
Nokogiri at_css
returns 一场 单场(第一场)比赛。使用 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",
... ]
请注意,要解析其余成员,您需要处理分页。 IE。从所有其他页面获取数据:
http://github.com/.../stargazers?page=NN
...其中 NN 是页码。
使用GithubAPI
一种更可靠的方法是使用 Github 观星者列表 API:
https://developer.github.com/v3/activity/starring/#list-stargazers
我写了一个小脚本来从 Github 中提取用户名。我可以获取第一个用户名的详细信息,但我不明白如何使用相同的 CSS 选择器 class 遍历元素列表以将用户名列表放在一起:
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-...
元素并将值存储在某个数组中吗?
Nokogiri at_css
returns 一场 单场(第一场)比赛。使用 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",
... ]
请注意,要解析其余成员,您需要处理分页。 IE。从所有其他页面获取数据:
http://github.com/.../stargazers?page=NN
...其中 NN 是页码。
使用GithubAPI
一种更可靠的方法是使用 Github 观星者列表 API: https://developer.github.com/v3/activity/starring/#list-stargazers