Ruby 需要基于配方的网页解析概念

Ruby 需要基于配方的网页解析概念,ruby,parsing,rules,Ruby,Parsing,Rules,我正在开发一个网页抓取解决方案,它可以抓取完全不同的网页,让用户定义规则/脚本,以便从网页中提取信息。 我从一个域开始抓取,并基于Nokogiri构建了一个解析器。 基本上一切正常。 现在,每当有人想要添加具有不同布局/样式的网页时,我都可以添加一个ruby类。 相反,我考虑使用一种方法,用户使用xpath指定存储内容的元素,并将其存储为该网页的一种方法 示例:用户希望使用哈希(column name=>cell content)提取行,从而获得一个表结构 我曾经考虑编写一个ruby函数来提取这

我正在开发一个网页抓取解决方案,它可以抓取完全不同的网页,让用户定义规则/脚本,以便从网页中提取信息。 我从一个域开始抓取,并基于Nokogiri构建了一个解析器。 基本上一切正常。 现在,每当有人想要添加具有不同布局/样式的网页时,我都可以添加一个ruby类。 相反,我考虑使用一种方法,用户使用xpath指定存储内容的元素,并将其存储为该网页的一种方法

示例:用户希望使用哈希(column name=>cell content)提取行,从而获得一个表结构

我曾经考虑编写一个ruby函数来提取这个通用表信息:

# extracts a table's rows as an array of hashes (column_name => cell content)
# html - the html-file as a string
# xpath_table - specifies the html table as xpath which hold the data to be extracted

def basic_table(html, xpath_table)
  xpath_headers = "#{xpath_table}/thead/tr/th"
  html_doc = Nokogiri::HTML(html)   

  html_doc = Nokogiri::HTML(html)
  row_headers = html_doc.xpath(xpath_headers)
  row_headers = row_headers.map do |column|
    column.inner_text
  end

  row_contents = Array.new

  table_rows  = html_doc.xpath('#{xpath_table}/tbody/tr')
  table_rows.each do |table_row|    

    cells = table_row.xpath('td')
    cells = cells.map do |cell|
        cell.inner_text
    end

    row_content_hash = Hash.new
    cells.each_with_index do |cell_string, column_index|
        row_content_hash[row_headers[column_index]] = cell_string
    end

    row_contents << [row_content_hash]
  end
  return row_contents
end
#将表的行提取为哈希数组(列名称=>单元格内容)
#html-作为字符串的html文件
#xpath_table-将html表指定为xpath,其中包含要提取的数据
def basic_表(html、xpath_表)
xpath_headers=“#{xpath_table}/thead/tr/th”
html_doc=Nokogiri::html(html)
html_doc=Nokogiri::html(html)
行标题=html\u doc.xpath(xpath\u标题)
row_headers=row_headers.map do |列|
column.inner\u文本
结束
行内容=Array.new
table_rows=html_doc.xpath('#{xpath_table}/tbody/tr')
表|u行。每个do |表|u行|
cells=table_row.xpath('td')
cells=cells.map do | cell|
cell.inner\u文本
结束
行\u内容\u哈希=hash.new
cells.each_与_索引do | cell_字符串,column_索引|
行内容散列[行标题[列索引]]=单元格字符串
结束
行内容
<basic_table xpath='//div[@id="grid"]/table[@id="displayGrid"]'