我正在尝试使用 Hpricot 来获取具有我不知道的类名的跨度内的值。我知道它遵循“foo_[几个数字]_bar”的模式。
现在,我将整个包含元素作为字符串获取,并使用正则表达式解析标签的字符串。该解决方案有效,但看起来真的很难看。
doc = Hpricot(open("http://scrape.example.com/search?q=#{ticker_symbol}"))
elements = doc.search("//span[@class='pr']").inner_html
string = ""
elements.each do |attr|
if(attr =~ /foo_\d+_bar/)
string = attr
end
end
# get rid of the span tags, just get the value
string.sub!(/<\/span>/, "")
string.sub!(/<span.+>/, "")
return string
似乎应该有更好的方法来做到这一点。我想做类似的事情:
elements = doc.search("//span[@class='" + /foo_\d+_bar/ + "']").inner_html
但这行不通。有没有办法用正则表达式搜索?