【发布时间】:2016-12-12 05:37:54
【问题描述】:
这段代码应该可以获取任何网页的内容:
require 'socket'
host = 'www.tutorialspoint.com' # The web server
port = 80 # Default HTTP port
path = "/index.htm" # The file we want
# This is the HTTP request we send to fetch a file
request = "GET #{path} HTTP/1.0\r\n\r\n"
socket = TCPSocket.open(host,port) # Connect to server
socket.print(request) # Send request
response = socket.read # Read complete response
# Split response at first blank line into headers and body
headers,body = response.split("\r\n\r\n", 2)
puts headers
puts body
当我在命令行中运行它时,我得到一个 404 错误,但是当我去 www.tutorialspoint.com/index.htm 时它就在那里,那是什么?:
虽然,我使用 open-uri 库来获取网页内容没有问题。不过我想知道这个怎么用。
【问题讨论】: