首页 > 解决方案 > 如何摆脱数组中的幻像行?

问题描述

我正在用 httparty 抓取一堆表格,然后用 nokogiri 解析响应。一切正常,但随后我在顶部得到一个幻影行:

require 'nokogiri'
require 'httparty'
require 'byebug'
def scraper
    url = "https://github.com/public-apis/public-apis"
    parsed_page = Nokogiri::HTML(HTTParty.get(url))
    # Get categories from the ul at the top
    categories = parsed_page.xpath('/html/body/div[4]/div/main/div[2]/div/div/div/article/ul/li/a')
    # Get all tables from the page
    tables = parsed_page.xpath('/html/body/div[4]/div/main/div[2]/div/div/div/article/table')
    rows = []
    # Acting on one first for testing before making it dynamic 
    tables[0].search('tr').each do |tr|
        cells = tr.search('td')
        link = ''
        values = []
        row = {
            'name' => '',
            'description' => '',
            'auth' => '',
            'https' => '',
            'cors' => '',
            'category' => '',
            'url' => ''
        }
        cells.css('a').each do |a|
            link += a['href']
        end
        cells.each do |cell|
            values << cell.text
        end
        values << categories[0].text
        values << link
        rows << row.keys.zip(values).to_h
    end
    puts rows
end
scraper

结果在控制台:

{"name"=>"Animals", "description"=>"", "auth"=>nil, "https"=>nil, "cors"=>nil, "category"=>nil, "url"=>nil}
{"name"=>"Cat Facts", "description"=>"Daily cat facts", "auth"=>"No", "https"=>"Yes", 
...

第一排是哪里来的?

标签: arraysrubyhashnokogiri

解决方案


您看到的第一行很可能是标题行。标题行使用<th>而不是<td>. 这意味着cells = tr.search('td')标题行将是一个空集合。

在大多数情况下,标题行放在 中<thead>,数据行放在 中<tbody>。因此,tables[0].search('tr')您可以不这样做tables[0].search('tbody tr'),而是只选择<tbody>标签中的行。


推荐阅读