所以我有这个代码收集我需要的所有产品信息:
# get main page
page = agent.get "http://www.site.com.mx/tienda/index.php"
search_form = page.forms.first
search_result = agent.submit search_form
doc = Nokogiri::HTML(search_result.body)
rows = doc.css("table.articulos tr")
i = 0
details = rows.collect do |row|
detail = {}
[
[:sku, 'td[3]/text()'],
[:desc, 'td[4]/text()'],
[:qty, 'td[5]/text()'],
[:qty2, 'td[5]/p/b/text()'],
[:price, 'td[6]/text()']
].collect do |name, xpath|
detail[name] = row.at_xpath(xpath).to_s.strip
end
i = i + 1
detail
end
如果qty2只存在,我需要像我的代码一样收集SKU(在变量中)。
答案 0 :(得分:0)
如果我的问题是对的:
rows.collect{...}.reject{|detail| detail[:qty2].empty?}
或
rows.inject([]){ |details, row| ... ; detail[:qty2].empty? ? details : details.push(detail) }
答案 1 :(得分:0)
修改行选择逻辑以仅获取所需的行。 更新:这会使执行的行在数量单元格中具有粗体:
rows = doc.xpath('//table[@class="articulos"]/tr[td[5]/p/b]')
更新2
以下是一个显示此功能的示例。
require 'nokogiri'
html = <<__html__
<html>
<table class="articulos">
<tr>
<td>1</td>
<td>2</td>
<td>sku1</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>2-1</td>
<td>2-2</td>
<td>sku2</td>
<td>2-4</td>
<td><p><b>2-5</b></p></td>
<td>2-6</td>
</tr>
</table>
</html>
__html__
doc = Nokogiri::HTML(html)
doc.xpath('//table[@class="articulos"]/tr[td[5]/p/b]').each do |row|
puts row.at_xpath('td[3]/text()')
end
输出:
sku2