arrays - 如何摆脱数组中的幻像行?
问题描述
我正在用 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",
...
第一排是哪里来的?
解决方案
您看到的第一行很可能是标题行。标题行使用<th>
而不是<td>
. 这意味着cells = tr.search('td')
标题行将是一个空集合。
在大多数情况下,标题行放在 中<thead>
,数据行放在 中<tbody>
。因此,tables[0].search('tr')
您可以不这样做tables[0].search('tbody tr')
,而是只选择<tbody>
标签中的行。
推荐阅读
- ios - 'imageEdgeInsets' 在 iOS 15.0 中已弃用
- html - 如何在灯箱画廊和创建页脚之后定义新的划分类?
- vaadin - 如何在 Vaadin 8 中将转换器添加到网格列?
- javascript - Express 应用程序在使用部分时给出了意外的输出
- r - Caret 中用于 mlpML 的激活函数
- python - 当使用 tkinter 再次按下具有初始功能的按钮时,如何添加和执行另一个功能?
- python - yfinance json.decoder.JSONDecodeError
- r - 增加一栏,根据学生情况和剩余名额分配愿望
- flutter - NoSuchMethodError:在 null 上调用了方法“[]”。接收方:空。尝试调用:[]("duyuru")
- reactjs - 当前未启用对实验语法“jsx”的支持 (11:9):