1

我有这样的事情:

require 'nokogiri'
require 'open-uri'
require 'csv'

fields = ['Full name', 'Address', 'Valid phone', 'E-mail']
availableFields = []
availableDataFields = []

CSV.open('myfile4.csv', 'a', {:col_sep => ';', :force_quotes => true}) do |csv|
    doc = Nokogiri::HTML(open(some_of_my_urls))

    #We are on the right page if we have content in this tag
    if doc.xpath('//div[@class = "pad8"]/h3').length > 0

        availableFields << 'Full name'
        availableFields << doc.xpath('//div[@class = "pad8"]/div[@class = "block pad8"]/table/tr/td[1]').text.gsub(/\n+|\r/, "").strip.split(':')
        #We received and parsed available fields on this page from td[1]
        #availableFields = ['Full name', 'Address', 'E-mail']

        availableDataFields << doc.xpath('//div[@class = "pad8"]/h3').text
        availableDataFields << doc.xpath('//div[@class = "pad8"]/div[@class = "block pad8"]/table/tr/td[3]').text.gsub(/\n+|\r/, "").strip
        #We received and parsed available fields data on this page from another td (td[3])
        #availableDataFields = ['John Doe', 'New York', 'john.doe@mail.com']

    end

    #Write to CSV file
    csv << fields
    csv << availableDataFields

end

所以当我打开 CSV 文件时,我有这个:

------------------------------------------------------------------------------------------------------
|     Full name    |    Address   |         Valid phone       |              E-mail                  |
| ---------------------------------------------------------------------------------------------------|
|     John Doe     |   New York   |      john.doe@mail.com    |                                      |
------------------------------------------------------------------------------------------------------

而不是这个

------------------------------------------------------------------------------------------------------
|     Full name    |    Address   |         Valid phone       |               E-mail                 |
| ---------------------------------------------------------------------------------------------------|
|     John Doe     |   New York   |                           |          john.doe@mail.com           |
------------------------------------------------------------------------------------------------------

因为我的某些some_of_my_urls页面fields

我该如何正确解决这个问题以及我如何(可能)使用availableFields它。也许比较fieldsandavailableFields并基于此生成正确的 csv 数据行?但是怎么做?

编辑:这是 HTML 代码:案例 1案例 2

4

0 回答 0