Parsing table could be difficult when its structure contains colspan or rowspan. TableParser parser HTML tables, group them by columns, with colspan and rowspan respected.
-
Nokogiri
-
sudo gem install table_parser
Use TableParser::Table to create parsed HTML table.
For example, following code: html = “<html><body><table><tr><td>A</td><td>B</td></tr>\ <tr><td rowspan="2">1</td><td>2</td></tr> \ <tr><td>3</td></tr></table></body></html>” doc = Nokogiri::HTML(html) table = TableParser::Table.new doc, “/html/body/table”
Result in following parsed table:
Table<TableColumn<name=A, children=[1],[1]>,TableColumn<name=B, children=[2],[3]>>
Note the first column contains duplicated item, because the first row contains “rowspan” element. If this is not desired, use following syntax to skip duplication:
html = “<html><body><table><tr><td>A</td><td>B</td></tr>\ <tr><td rowspan="2">1</td><td>2</td></tr> \ <tr><td>3</td></tr></table></body></html>” doc = Nokogiri::HTML(html) table = TableParser::Table.new doc, “/html/body/table”, {:dup_rows => false})
Which result in following parsed table:
Table<TableColumn<name=A, children=[1]>,TableColumn<name=B, children=[2],[3]>>
Read the spec (test/test_table_parser.rb) for more usage.
-
Francis Chong, francis at ignition dot hk
The MIT License
Copyright © 2010 Ignition Soft
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.