即使在我试图做的事情上,我也可能离得很远,但这是我得到的。
我喜欢收集幻想足球投影,并将所有的html元素(对于不同的球员)放在一个数组中,并遍历它们来显示结果。
require 'mechanize'
mechanize = Mechanize.new
dk_qb = mechanize.get('http://www.numberfire.com/nfl/fantasy/fantasy-football-projections/qb')
dk_qb_array = ['#container > div > div > div:nth-child(2) > div.fl.clearfix > h2',
'#container > div > div > div:nth-child(3) > div.fl.clearfix > h2']
dk_qb_array.each do |name|
require 'mechanize'
mechanize = Mechanize.new
dk_qb = mechanize.get('http://www.numberfire.com/nfl/fantasy/fantasy-football-projections/qb')
puts "#{dk_qb}.at('#{name}').text.strip"结束
returns ==> #<Mechanize::Page:0x007f9ed95058f0>.at('#container > div > div > div:nth-child(2) > div.fl.clearfix > h2').text.strip
#<Mechanize::Page:0x007f9ed91382e0>.at('#container > div > div > div:nth-child(3) > div.fl.clearfix > h2').text.strip我让它一次只能工作一次,但是任何关于迭代更多元素的建议都会很感激。
发布于 2014-08-14 19:39:19
您不需要在这里再次要求机械化:
dk_qb_array.each do |name|
require 'mechanize'无论如何,您应该使用Nokogiri--而不是机械化:
$ gem install nokogiri然后:
require 'nokogiri'
require 'open-uri'
selectors = [
'#container > div > div > div:nth-child(2) > div.fl.clearfix > h2',
'#container > div > div > div:nth-child(3) > div.fl.clearfix > h2',
]
url = 'http://www.numberfire.com/nfl/fantasy/fantasy-football-projections/qb'
doc = Nokogiri::HTML(open(url))
selectors.each do |selector|
puts selector
doc.css(selector).each do |matching_tag|
puts "\t #{matching_tag.text}"
end
end
--output:--
#container > div > div > div:nth-child(2) > div.fl.clearfix > h2
Week 1 Fantasy Football QB Projections
#container > div > div > div:nth-child(3) > div.fl.clearfix > h2从输出中可以看出,您的第二个选择器没有匹配;第一个选择器的单个匹配可能不是您想要的。整个页面上只有一个<h2>,所以寻找第二个是行不通的。
更好的方法是使用id属性直接到达您想要的区域。
"tbody#projection-data > tr"然后做这样的事情:
doc.css("tbody#projection-data > tr").each do |tr|
#The <tr> contains the data for one player
tr.css('td').each do |td| #Now step through the <td>'s for the given <tr>/player
puts td.text.strip
end
puts '-' * 10 #Marks the end of the data for one <tr>/player
#Now, loop back up and get the next <tr>/player
end
--output:--
Drew Brees (QB, NO)
ATL
#26
1
1
27.49/40.64
335.01
3.07
0.71
2.84
10.42
0.06
17.4-33.58
25.49
29.33
$0
0
26.25
$0
0
25.54
$0
0
25.54
$0
0
26.25
$0
0
----------
Peyton Manning (QB, DEN)
...
...https://stackoverflow.com/questions/25315961
复制相似问题