问题
so I have this code that collects all product info I need:
# 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
I need to collect SKU as in my code (in a variable) if qty2 exists only.
回答1:
Modify your row selection logic to get only the rows you want. Update: This will get the rows that do have the bold in the quantity cell:
rows = doc.xpath('//table[@class="articulos"]/tr[td[5]/p/b]')
Update 2
Here's an example showing that this works.
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
Output:
sku2
回答2:
If I get your question right:
rows.collect{...}.reject{|detail| detail[:qty2].empty?}
or
rows.inject([]){ |details, row| ... ; detail[:qty2].empty? ? details : details.push(detail) }
来源:https://stackoverflow.com/questions/6433808/how-to-parse-a-row-only-if-one-of-its-fields-is-bold-nokogiri-and-ruby