通过 Nokogiri 从 HTTP GET 响应正文中获取值? [英] Get value from a HTTP GET response body via Nokogiri?
问题描述
我从一个 HTTP 页面得到这个结果:
I get this result from a HTTP page like:
<!DOCTYPE html>
<html>
<head>
<title>Captchaservice</title>
</head>
<body>
15
</body>
</html>
我使用这个 Nokogiri 代码:
And I use this Nokogiri code:
doc = Nokogiri::HTML( response )
id = doc.xpath('//').text
但我得到 \n 15 \n
等
我试着写:
id = doc.xpath('//').text.to_i
我得到了这个值,但是当我使用这个 ID 时,我得到:
And I get this value, but when I use this ID I get:
undefined method `empty?' for 15:Fixnum
我做错了什么,如何获得这个整数值?
What am I doing wrong and how do I to get this integer value?
推荐答案
那是因为你的 id
是 Fixnum
类的实例(如 id
由于 doc.xpath('//').text.to_i
保持值 15.而 Fixnum
类没有 #empty?
方法.所以如果你想做空测试,那就做 id = doc.xpath('//').text.strip
.现在您的 id
将有一个字符串实例,即 '15'
.在此您可以调用 #empty?
方法.当您需要使用整数值时,只需执行 id.to_i
并使用它.
That's because your id
is an instance of Fixnum
class(as id
holds the value 15 due to doc.xpath('//').text.to_i
). And Fixnum
class don't have #empty?
method.So if you want to do empty test,then do id = doc.xpath('//').text.strip
. Now your id
will be having an string instance i.e. '15'
. On this you can call #empty?
method. when you need to use the integer value,there just do id.to_i
and use it.
这篇关于通过 Nokogiri 从 HTTP GET 响应正文中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!