由于反斜杠,Nokogiri忽略了第一个属性之后的所有内容?

时间:2013-05-17 12:44:51

标签: ruby-on-rails ruby nokogiri

为什么Nokogiri会因为反斜杠而忽略第一个属性后的所有内容?

我不确定为什么会这样做:

[12] pry(Template)> b
=> "<td style=\\\"color:#fff; padding:3px; font-size:11px; text-align:center;\\\">Home Improvement Agreement: Electrical Services & Standby Generators</td>"
[13] pry(Template)> Nokogiri::HTML.parse(b).to_html
=> "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><td style='\\\"color:#fff;' padding:3px font-size:11px text-align:center>Home Improvement Agreement: Electrical Services &amp; Standby Generators</td></body></html>\n"

注意它是如何产生错误的HTML的,就像在<td>元素中的颜色属性之后的所有内容一样。它关闭了属性,并将其余的变量分配为HTML name标签。

我很好奇是否有人知道为什么Nokogiri会这样做,以及我可以做些什么来绕过它呢?

3 个答案:

答案 0 :(得分:2)

你要求它解析这个:

<td style=\"color:#fff; ...\">

无效。这是有效的:

<td style="color:#fff; ...">

答案 1 :(得分:0)

尝试:

'<td style="color:#fff; padding:3px; font-size:11px; text-align:center;">Home Improvement Agreement: Electrical Services & Standby Generators</td>'

答案 2 :(得分:0)

Nokogiri可以很容易地判断解析HTML或XML文档是否存在问题:

require 'nokogiri'

html = '<td style=\"color:#fff; padding:3px; font-size:11px; text-align:center;\">Home Improvement Agreement: Electrical Services & Standby Generators</td>'
doc = Nokogiri::HTML.parse(html)
doc.errors
=> [#<Nokogiri::XML::SyntaxError: error parsing attribute name>, #<Nokogiri::XML::SyntaxError: error parsing attribute name>, #<Nokogiri::XML::SyntaxError: error parsing attribute name>, #<Nokogiri::XML::SyntaxError: htmlParseEntityRef: no name>]