如何使用mechanize/nokogiri获得简单但格式化的HTML?

Rad*_*dek 2 ruby mechanize nokogiri

require 'rubygems'
require 'mechanize'

  rational = Mechanize.new { |agent|
        agent.user_agent_alias = 'Windows Mozilla'
  }
  results = rational.get(ARGV[0])
  puts results.content 
Run Code Online (Sandbox Code Playgroud)

给我HTML,但我想要纯文本.最好的是它是否可以格式化.

Dan*_*ara 5

此代码将为您提供整个文档的简单无格式文本:

require 'mechanize'
require 'nokogiri'

rational = Mechanize.new { |agent|
    agent.user_agent_alias = 'Windows Mozilla'
}

document = Nokogiri::HTML(rational.get(ARGV[0]).content)

#This will give you very dirty result
#results = document.inner_text

#My suggestion is to extract text from some specific element
results = document.css("#content .my-element-with-some-contents").inner_text
Run Code Online (Sandbox Code Playgroud)

  • 不需要解析响应,你可以像`rational.get(link); rational.page.at( '/ HTML /体/ H1').text` (2认同)