0

新来的,想知道如何从特定的 URL 获取数据并将相应的数据存储在数据库中,然后使用 Rails 访问它。

但是,我能够从 URL 获取数据并以 XML 格式接收数据并能够显示它,但这是手动完成的,我只想知道如何从 URL 获取数据,因为它是Hash形式,包含很多属性。

需要将这些属性存储在数据库中并直接从 URL 中检索值。

4

2 回答 2

1
for that use Nokogiri gem for more information you can read from http://nokogiri.org/tutorials/parsing_an_html_xml_document.html

I also gives you following commands of nokogiri... please avoide # sign

doc = Nokogiri::HTML(open(your site url))
# get all specific selector's all matching elements
# doc.css("div")

# get specific selector's first matching element
# doc.at_css("div")

# get matching element by id name
# doc.at_css("input#id name")
# eg: doc.at_css("input#ResultsCount")

# get matching element by class name
# doc.at_css("div.class name")
# eg: doc.at_css("div.results")


# File.open("#{Rails.root}/public/aa.txt","w+").write(doc.css("div#search-result-listings"))

# get fields data eg. take a value of input field whose id ResultsCount
# <input type="hidden" name="ResultsCount" id="ResultsCount" value="12321" />
# doc.at_css("input#ResultsCount")["value"]

# get all results
# search_results=doc.at_css("div#search-result-listings").css("div.result.clearfix")


#find by tag ("<ul>") and find their elements and children
dc=doc.at_css("div#search-result-listings")
#find all elements of ul such as li with their childs
dc.at_css("ul").elements
#if only childs of elements
dc.at_css("ul").elements.children
#if you want to print that child value then use "text" property
dc.at_css("ul").elements.children[0].text
#if you want all child data then use
dc.at_css("ul").elements.children.text
or
dc.at_css("ul").elements.text
or
dc.at_css("ul").text
于 2013-10-07T13:33:37.290 回答
0

您可以使用Mechanize获取页面,使用Nokogiri解析内容并使用Nokogiri::XML::Builder(或Builder )从接收到的数据构建 XML或将其存储在数据库中。

于 2013-10-07T06:31:17.130 回答