无法使用Mechanize识别正确的CSS选择器

问题描述 投票:0回答:1

我已经构建了一个web scraper,它正在成功地从我正在查看的网页中提取我需要的所有内容。目标是拉出与在特定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选择器,但所有内容都是零或空白。

<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">

我在的coffee_page就在这里:https://shop.ceremonycoffee.com/products/burundi-kiryama

ruby-on-rails ruby nokogiri mechanize
1个回答
0
投票

你需要改变

bean.image_url = coffee_page.css('img data-featured-product-image').attr('src')

bean.image_url = coffee_page.css('#mobile-only>img').attr('src')

如果可以,请始终使用附近的标识符来查找要访问的元素。

© www.soinside.com 2019 - 2024. All rights reserved.