如何在Ruby中获取网页的HTML源代码 [英] How to get the HTML source of a webpage in Ruby
本文介绍了如何在Ruby中获取网页的HTML源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Ruby中,是否有一个函数(也许是一个库)允许我将此HTML源代码存储为变量?像这样:
source = view_source(http://stackoverflow.com)
其中源代码为此文本:
<!DOCTYPE HTML PUBLIC - // W3C // DTD HTML 4.01 // ENhttp://www.w3.org/TR/html4/strict.dtd\">
< html>
< head>
< title>堆栈溢出< / title>
等
解决方案使用Net::HTTP :
require'net / http'
source = Net :: HTTP.get('stackoverflow.com','/index.html')
In browsers such as Firefox or Safari, with a website open, I can right click the page, and select something like: "View Page Source" or "View Source." This shows the HTML source for the page.
In Ruby, is there a function (maybe a library) that allows me to store this HTML source as a variable? Something like this:
source = view_source(http://stackoverflow.com)
where source would be this text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Stack Overflow</title> etc
解决方案Use Net::HTTP:
require 'net/http' source = Net::HTTP.get('stackoverflow.com', '/index.html')
这篇关于如何在Ruby中获取网页的HTML源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文