我编写了 Ruby scraper 从加利福尼亚参议院获取竞选财务数据,然后将每个人保存为哈希。这是到目前为止的代码:
这是主要网站:http ://cal-access.sos.ca.gov/Campaign/Candidates/
这是候选人页面的示例:http ://cal-access.sos.ca.gov/Campaign/Committees/Detail.aspx?id=1342974&session=2011&view=received
这是 github 存储库,如果您想在代码中查看我的评论:https ://github.com/aboutaaron/Baugh-For-Senate-2012/blob/master/final-exam.rb
上代码...
require 'nokogiri'
require 'open-uri'
campaign_data = Nokogiri::HTML(open('http://cal-access.sos.ca.gov/Campaign/Candidates/'))
class Candidate
def initialize(url)
@url = url
@cal_access_url = "http://cal-access.sos.ca.gov"
@nodes = Nokogiri::HTML(open(@cal_access_url + @url))
end
def get_summary
candidate_page = @nodes
{
:political_party => candidate_page.css('span.hdr15').text,
:current_status => candidate_page.css('td tr:nth-child(2) td:nth-child(2) .txt7')[0].text,
:last_report_date => candidate_page.css('td tr:nth-child(3) td:nth-child(2) .txt7')[0].text,
:reporting_period => candidate_page.css('td tr:nth-child(4) td:nth-child(2) .txt7')[0].text,
:contributions_this_period => candidate_page.css('td tr:nth-child(5) td:nth-child(2) .txt7')[0].text.gsub(/[$,](?=\d)/, ''),
:total_contributions_this_period => candidate_page.css('td tr:nth-child(6) td:nth-child(2) .txt7')[0].text.gsub(/[$,](?=\d)/, ''),
:expenditures_this_period => candidate_page.css('td tr:nth-child(7) td:nth-child(2) .txt7')[0].text.gsub(/[$,](?=\d)/, ''),
:total_expenditures_this_period => candidate_page.css('td tr:nth-child(8) td:nth-child(2) .txt7')[0].text.gsub(/[$,](?=\d)/, ''),
:ending_cash => candidate_page.css('td tr:nth-child(9) td:nth-child(2) .txt7')[0].text.gsub(/[$,](?=\d)/, '')
}
end
def get_contributors
contributions_received = @nodes
grab_contributor_page = @nodes.css("a.sublink6")[0]['href']
contributor_page = Nokogiri::HTML(open(@cal_access_url + grab_contributor_page))
grab_contributions_page = contributor_page.css("a")[25]["href"]
contributions_received = Nokogiri::HTML(open(@cal_access_url + grab_contributions_page))
puts
puts "#{@cal_access_url}" + "#{grab_contributions_page}"
puts
contributions_received.css("table").reduce([]) do |memo, contributors|
begin
memo << {
:name_of_contributor => contributions_received.css("table:nth-child(57) tr:nth-child(2) td:nth-child(1) .txt7").text
}
rescue NoMethodError => e
puts e.message
puts "Error on #{contributors}"
end
memo
end
end
end
campaign_data.css('a.sublink2').each do |candidates|
puts "Just grabbed the page for " + candidates.text
candidate = Candidate.new(candidates["href"])
p candidate.get_summary
end
get_summary
按计划工作。get_contributors
按计划存储第一个贡献者<td>
,但会执行 20 多次。在我弄清楚多重打印问题之前,我现在只选择获取名称。
最终目标是获得贡献者的哈希值以及他们所需的所有信息,并可能将它们移动到 SQL 数据库/Rails 应用程序中。但是,在此之前,我只想要一个工作刮刀。
有什么建议或指导吗?对不起,如果代码不是超级。编程的超级新手。