问题描述
我有一个变量e,用于存储Nokogiri :: XML :: Element对象。
执行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做到这一点
解决方法
如果要提取链接,可以使用:
e.at_css("a").attributes["href"].value
.at_css
返回与CSS选择器匹配的第一个元素(另一个Nokogiri::XML::Element
)。要获取所有匹配元素的列表,请改用.css
。
.attributes
为您提供了到Nokogiri::XML::Attr
的哈希映射属性名称。在此哈希(href
中查找所需的属性后,就可以调用.value
来获取实际的文本值。