【问题标题】:How to scarpe the href using Nokogiri如何使用 Nokogiri 抓取 href
【发布时间】:2020-10-17 12:34:49
【问题描述】:

我有一个存储 Nokogiri::XML::Element 对象的变量 e。

当我执行puts e 时,屏幕上会显示以下内容:

<h3 class="fixed-recipe-card__h3">
        <a href="https://www.allrecipes.com/recipe/21712/chocolate-covered-strawberries/" data-content-provider-id="" data-internal-referrer-link="hub recipe" class="fixed-recipe-card__title-link">
            <span class="fixed-recipe-card__title-link">Chocolate Covered Strawberries</span>
        </a>
    </h3>

我想刮这部分https://www.allrecipes.com/recipe/21712/chocolate-covered-strawberries/

如何使用 Nokogiri 来做到这一点

【问题讨论】:

    标签: ruby nokogiri


    【解决方案1】:

    如果要提取链接,可以使用:

    e.at_css("a").attributes["href"].value
    

    .at_css 返回匹配 CSS 选择器的第一个元素(另一个 Nokogiri::XML::Element)。要获取所有匹配元素的列表,请改用.css

    .attributes 为您提供到Nokogiri::XML::Attr 的哈希映射属性名称。在此哈希 (href) 中查找所需属性后,您可以调用 .value 来获取实际的文本值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 2017-11-09
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多