且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以使用Nokogiri解析样式表?

更新时间:2023-01-29 18:16:14

p> @molf肯定有一个很好的开始,但它仍然需要调试一些问题,使其在生产中工作。这是目前的测试版本:

@molf definitely had a great start there, but it still required debugging a handful of problems to get it working in production. Here is the current, tested version of this:

html = Nokogiri::HTML(html_string)
css = CssParser::Parser.new
css.add_block!(html_string) # Warning:  This line modifies the string passed into it.  In potentially bad ways.  Make sure the string has been duped and stored elsewhere before passing this.

css.each_selector do |selector, declarations, specificity|
  next unless selector =~ /^[\d\w\s\#\.\-]*$/ # Some of the selectors given by css_parser aren't actually selectors.
  begin
    elements = html.css(selector)
    elements.each do |match|
      match["style"] = [match["style"], declarations].compact.join(" ")
    end
  rescue
    logger.info("Couldn't parse selector '#{selector}'")
  end
end

html_with_inline_styles = html.to_s