【发布时间】:2019-03-19 06:58:08
【问题描述】:
我已经构建了一个网络抓取工具,它可以成功地将我正在查看的网页中几乎所有我需要的东西都提取出来。目标是提取与在特定 URL 中找到的所有咖啡相关联的特定图像的 URL。
我定义的完成抓取的rake任务如下:
mechanize = Mechanize.new
mechanize.get(url) do |page|
page.links_with(:href => /products/).each do |link|
coffee_page = link.click
bean = Bean.new
bean.acidity = coffee_page.css('[data-id="acidity"]').text.strip.gsub("acidity ","")
bean.elevation = coffee_page.css('[data-id="elevation"]').text.strip.gsub("elevation ","")
bean.roaster_id = "2"
bean.harvest_season = coffee_page.css('[data-id="harvest"]').text.strip.gsub("harvest ","")
bean.price = coffee_page.css('.price-wrap').text.gsub("$","")
bean.roast_profile = coffee_page.css('[data-id="roast"]').text.strip.gsub("roast ","")
bean.processing_type = coffee_page.css('[data-id="process"]').text.strip.gsub("process ","")
bean.cultivar = coffee_page.css('[data-id="cultivar"]').text.strip.gsub("cultivar ","")
bean.flavor_profiles = coffee_page.css('.price-wrap+ p').text.strip
bean.country_of_origin = coffee_page.css('#pdp-order h1').text.strip
bean.image_url = coffee_page.css('img data-featured-product-image').attr('src')
if bean.country_of_origin == "Origin Set" || bean.country_of_origin == "Gift Card (online use only)"
bean.destroy
else
ap bean
end
end
end
现在我需要的信息都在页面上,我正在寻找如下所示的图像 URL,但是对于源页面上的所有单独的 coffee_pages。它需要足够通用才能提取此图片源,但仅此而已。我尝试了许多不同的 css 选择器,但一切都是 nil 或空白。
<img src="//cdn.shopify.com/s/files/1/2220/0129/products/ceremony-product-gummy-bears_480x480.jpg?v=1551455589" alt="Burundi Kiryama" data-product-featured-image style="display:none">
我所在的咖啡页面在这里:https://shop.ceremonycoffee.com/products/burundi-kiryama
【问题讨论】:
-
Css 确实具有子字符串匹配,因此您可以使用
img[src^='//cdn.shopify.com/s/files/'](不确定这是否足以满足您的需求,如果需要,您可以将范围限定为父级)。见stackoverflow.com/questions/8903313/… 和w3.org/TR/selectors/#attribute-substrings -
如果我对您的问题的回答足够,请告诉我。如果是,请标记为正确。
-
请阅读“How to Ask”。当询问您的代码问题时,我们需要最少的数据来证明问题本身的问题。链接迫使我们搜索页面的 HTML,这会浪费我们的时间并阻止人们尝试帮助您。我们需要您准备问题,以便我们为您提供帮助。此外,既然链接已损坏,您的问题就没有什么意义了。
标签: ruby-on-rails ruby nokogiri mechanize