S
S
Stergy2018-09-03 14:07:50
API
Stergy, 2018-09-03 14:07:50

How to convert html to text in ruby(rails)?

3rd party Api returns error as html

<html><head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>500 Server Error</title>
</head>
<body text=#000000 bgcolor=#ffffff>
<h1>Error: Server Error</h1>
<h2>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. </h2>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. .</p>
</body></html>

How can I use Ruby(Rails) to convert this message so that it would display on the page not the html code coming from the API, but the text contained in the message.
I'm new, so I would be grateful for a detailed answer)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Blokhin, 2018-09-03
@Stergy

nokogiri.org

require 'nokogiri'

api_body_result = <<-HTML
<html>
  <head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <title>500 Server Error</title>
  </head>
<body text=#000000 bgcolor=#ffffff>
  <h1>Error: Server Error</h1>
  <h2>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. </h2>
  <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. .</p>
  </body>
</html>
HTML

doc = Nokogiri::HTML api_body_result

# source html inner text
text = doc.text

# or

# html title
title = doc.title

# html body
element = doc.at_css 'body'
body = element.text

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question