使用 nokogiri n Ruby on Rails 分别获取折扣前和折扣后的价格
我正在尝试学习废品这些值,我将其放入两个不同的任务中:
- 从整个文本中获取 35.00
- 从整个文本中获取 42.00
下面是 html:
<p style="font-size: 30px; margin-left: -10px; padding: 15px 0pt;">
$35.00 - $42.00
</p>
我用来获取整个文本的代码如下以下:
node = html_doc.at_css('p')
p node.text
I'm trying to learn on scrap these values which i put it in 2 different task:
- get the 35.00 from the entire text
- get the 42.00 from the entire text
below is the html:
<p style="font-size: 30px; margin-left: -10px; padding: 15px 0pt;">
$35.00 - $42.00
</p>
the code that im using to get the entire text is as below:
node = html_doc.at_css('p')
p node.text
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从
node.text
获取整个文本,这就是 Nokogiri 所需要的。从那里你可以使用scan
查找数字和一些列表争论 (flatten
和地图
)而你'重新完成。像这样的:这应该让您在
first
中得到 35.0,在second
中得到42.0
。如果您知道数字是带小数的价格,那么您可以稍微简化正则表达式:You can get the whole text from
node.text
and that's as far as you need to go with Nokogiri. From there you could usescan
to find the numbers and a bit of list wrangling (flatten
andmap
) and you're done. Something like this:That should leave you with 35.0 in
first
and42.0
insecond
. If you know that the numbers are prices with decimals then you can simplify the regex a bit:mu的答案是正确的,但使用 split/splat 似乎更简单。
mu's answer is correct but it seems simpler to use split/splat.