我正在使用YQL查询(标准示例查询,包含GOOG,YHOO,MSFT和AAPL)来为所有可用字段生成XML。一旦使用Ruby脚本生成XML输出,我想抓住YQL站点的XML输出,这样我就可以反复为不同的库存运行它并将数据存储在某个地方。我还没有完成我的剧本,但我似乎没有完成。这是代码:
yahoo_finance_scrape.rb
require 'rubygems'
require 'nokogiri'
require 'restclient'
PAGE_URL = "http://developer.yahoo.com/yql/console/"
yql_query = 'use "http://github.com/spullara/yql-tables/raw/d60732fd4fbe72e5d5bd2994ff27cf58ba4d3f84/yahoo/finance/yahoo.finance.quotes.xml"
as quotes; select * from quotes where symbol in ("YHOO","AAPL","GOOG","MSFT") '
if page = RestClient.post(PAGE_URL, {'name' => yql_query, 'submit' => 'Test'})
puts "YQL query: #{yql_query}, is valid"
xml_output = Nokogiri::HTML(page)
lines = xml_output.css('#container #layout-doc #yui-gen3000008 #yui-gen3000009 #yui_3_11_0_3_1393417778356_354
#yui-gen3000015 #yui-gen3000016 div#yui_3_11_0_2_1393417778356_10 #centerBottomView
#outputContainer div#output #outputTabContent #formattedView #viewContent #prexml')
lines.each do |line|
puts line.css('span').map{|span| span.text}.join(' ')
sleep 0.03
end
end
当我运行程序时,它只会打印 “YQL查询:使用”http://github.com/spullara/yql-tables/raw/d60732fd4fbe72e5d5bd2994ff27cf58ba4d3f84/yahoo/finance/yahoo.finance.quotes.xml“ 作为报价; select * from quotes其中符号(“YHOO”,“AAPL”,“GOOG”,“MSFT”)有效“ 然后停下来。哦,我正在使用那个Github网址,因为yahoo.finance.quotes不起作用,Stackoverflow上的其他人建议使用它。
如果你想检查css标签,只需转到http://developer.yahoo.com/yql/console/并输入我的查询并在其上执行检查元素。我会在这里发布,但我不知道如何。
答案 0 :(得分:0)
输出只是yql_query var的内容。所以这没什么用。
您可能不应该在代码中将“使用xxxx ax引号”作为字符串。 看看“其他人”的想法。
RestClient.post()
方法返回响应对象。对于所有HTTP操作,请始终检查response.code,否则您不知道错误。
response = RestClient.post(...)
puts "HTTP Response code: #{response.code}"
if response.code == 200
page = repsonse.to_str
...
end
根据Nokogiri网站的说法,xml_output.css()方法过滤它就像是一个css选择器。如果你有例如“#container#layout-doc”,这意味着“在id'容器'的元素内部过滤具有id'layout-doc'的元素,依此类推。这真的是你想要做的吗?如果是的话,最后一个“#prexml”应该足够且容易出错,因为id通常应该是唯一的。