我有一个循环,输出我从网站抓取的一些信息。为了使信息以可读的方式显示,我在字符串中添加了<br>
。但是当它运行时,它显示<br>
,转义html。我使用过html_safe和raw但是都没有用。代码有什么问题?代码在视图主页中调用(不用担心,一旦代码工作,我将移动它。)
<%=
require 'rubygems'
require 'nokogiri'
require 'open-uri'
time = Time.new
month = I18n.t("date.abbr_month_names")[time.month]
day = time.day
"#{month} #{day}"
#United States
cities = [
"sfbay", "losangeles", "athensga", "phoenix", "santabarbara", "denver",
"panamacity", "miami", "austin", "bakersfield", "keys", "newyork"
]
cities.map do |city|
#Search Terms
search_terms = ["mechanic", "car", "tech"]
search_terms.map do |term|
escaped_term = CGI.escape(term)
url = "http://#{city}.craigslist.org/search/jjj?query=#{escaped_term}&catAbb=jjj&
srchType=A"
doc = Nokogiri::HTML(open(url))
doc.css(".row").map do |row|
date = row.css(".itemdate").text
a_tag = row.css("a")[0]
text = a_tag.text
link = a_tag[:href]
if date = "#{month} #{day}"
@strings << "#{date} #{text} #{link}"
end
end
end
end
%>
答案 0 :(得分:0)
doc.css(".row").map do |row|
date = row.css(".itemdate").text
a_tag = row.css("a")[0]
text = a_tag.text
link = a_tag[:href]
if date = "#{month} #{day}"
"<br/>".html_safe + "#{date} #{text} #{link}"
end
end
答案 1 :(得分:0)
嗯根本不确定但是尝试以下方法:
doc.css(".row").map do |row|
date = row.css(".itemdate").text
a_tag = row.css("a")[0]
text = a_tag.text
link = a_tag[:href]
if date = "#{month} #{day}"
@string = "#{date} #{text} #{link}<br />"
end
end.html_safe
另一种方式,不解决你的问题,而是在每一行显示br:
# in controller or whatever
@strings = []
if date = "#{month} #{day}"
@strings << "#{date} #{text} #{link}"
end
# in the view:
<%= raw(@strings.join('<br />')) %>