所以,我是ruby的新手,正在玩一个简单的抓取脚本。我写了以下内容:
class Scrape
def get_attribute(html, doc)
doc.css(html).to_s.strip.remove_html_tags
end
public
def remove_html_tags
re = /<("[^"]*"|'[^']*'|[^'">])*>/
self.gsub!(re, '')
end
end
有被排除的方法,但是我将我的错误回到了这个方法,每当调用get_attribute方法时我都会得到以下内容:
NoMethodError: undefined method `remove_html_tags' for #<String:0x007fcf42fd5610>
唯一可行的是当我直接在字符串上使用gsub时:
def get_attribute(html, doc)
doc.css(html).to_s.strip.gsub(/<("[^"]*"|'[^']*'|[^'">])*>/, '')
end
我已尝试在模块中包含此remove_html_tags方法,但这似乎没有帮助。我无法弄清楚我错过了什么,任何帮助都将不胜感激!
答案 0 :(得分:2)
您是否想要使用类Scrape
中定义的方法,您应该知道关于:
# string call string’s method
doc.css(html).to_s.strip.remove_html_tags
应该更改为:
# scrape call scrape’s method
self.remove_html_tags(doc.css(html).to_s.strip)
remove_html_tags
本身应该对字符串实例进行操作:
# parameter
def remove_html_tags input
re = /<("[^"]*"|'[^']*'|[^'">])*>/
# gsubbing parameter
input.gsub(re, '') # using gsub not gsub! to _return_ correct result
end
答案 1 :(得分:1)
doc.css(html).to_s.strip
正在为您提供String
个实例,因此您需要在类remove_html_tags
中定义方法String
。目前它是类Scarpe
的实例方法,但您在String
的实例上调用它。
您可以按如下方式设计方法: -
class Scrape
def get_attribute(html, doc)
string = remove_html_tags doc.css(html).to_s.strip
end
private
def remove_html_tags(string)
re = /<("[^"]*"|'[^']*'|[^'">])*>/
string.gsub(re, '')
end
end
注意:如果您不想将remove_html_tags
公开给外部API,则应将其设为private
方法,否则,将其设为{{} 1}}。如果是公开的,不需要使用public
关键字,默认情况下,所有方法的可见性都属于public
。