Retrieve contents of URL as string

前端 未结 7 643
温柔的废话
温柔的废话 2020-12-25 12:57

For tedious reasons to do with Hpricot, I need to write a function that is passed a URL, and returns the whole contents of the page as a single string.

I\'m close.

7条回答
  •  一生所求
    2020-12-25 13:50

    You can do the same without OpenURI:

    require 'net/http'
    require 'uri'
    
    def open(url)
      Net::HTTP.get(URI.parse(url))
    end
    
    page_content = open('http://www.google.com')
    puts page_content
    

    Or, more succinctly:

    Net::HTTP.get(URI.parse('http://www.google.com'))
    

提交回复
热议问题