【问题标题】:DOMDocument in Ruby on RailsRuby on Rails 中的 DOMDocument
【发布时间】:2015-08-26 09:27:31
【问题描述】:

只是想知道是否可以将此php脚本转换为rails

$c = file_get_contents('http://www.bunnings.com.au/products_category_plumbing-supplies_1637.aspx'); 
$dom = new DOMDocument();
$dom->loadHTML($c);    
$xpath = new DOMXPath($dom);
$div = $xpath->query('//div[@class="details"]');

echo '<table>';

foreach($div as $details)
{
    $name = $details->getElementsByTagName('h4')->item(0)->getElementsByTagName('a')->item(0)->nodeValue;
    $price = $details->getElementsByTagName('p')->item(0)->getElementsByTagName('span')->item(0)->nodeValue;
    $itemNumber = $details->getElementsByTagName('p')->item(0)->childNodes->item(2)->nodeValue;

    $html = '<tr>';
    $html .= '<td>' . htmlspecialchars($name) . '</td>';
    $html .= '<td>' . htmlspecialchars($price) . '</td>';
    $html .= '<td>' . htmlspecialchars($itemNumber) . '</td>';
    $html .= '</tr>';

    echo $html;
}

echo '</table>';

【问题讨论】:

  • 为什么不可能?
  • 我在 Rails 中找不到类似的函数
  • 您正在尝试提取 html 文档并将其放在您的页面上?当然这是可能的。有这方面的宝石。
  • @HristoGeorgiev 是的,我正在查看 httparty gem 看起来可能有用

标签: php ruby-on-rails xml domdocument data-conversion


【解决方案1】:

Rails 是用于 Web 应用程序的 Ruby 框架。您需要的是一个简单的 Ruby 脚本(当然,您可以将其集成到更大的 Rails 应用程序中)。

您可以使用 nokogiri gem 来解析 HTML。在您的终端上:

gem install nokogiri

然后像这样创建一个新的 .rb 文件:

require 'open-uri'
require 'nokogiri'

url = 'http://www.bunnings.com.au/products_category_plumbing-supplies_1637.aspx'
doc = Nokogiri::HTML(open(url))

div = doc.xpath('//div[@class="details"]')

# Well, I guess you should continue now

有关 Nokogiri 示例,请参阅 http://www.nokogiri.org/tutorials/searching_a_xml_html_document.html

【讨论】:

    猜你喜欢
    • 2020-10-02
    • 2013-02-13
    • 2021-10-29
    • 2012-06-17
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    相关资源
    最近更新 更多