2014-03-30 31 views
1

应该获取给定网站源代码的ruby代码不起作用。它说,该网站不存在。无法使用ruby获取页面源代码

require 'uri' 
require 'net/http' 
uri = URI.parse("http://nice.com/careers?category=170") 
http = Net::HTTP.new(uri.host, uri.port) 
request = Net::HTTP::Get.new(uri.request_uri) 
response=http.request(request) 
@data = response.body 

它可以与其他网站一起使用。

  1. 为什么?
  2. 如何解决?
+0

只要运行这个,我得到了一个重定向代码。你确定它说网站不存在吗? – BroiSatse

回答

2

我总是喜欢在命令行上使用curl来检查内容。

在这种情况下它原来http://nice.com/careers?category=170请求给你一个HTTP 301重定向到同一域但www.

curl -I "http://nice.com/careers?category=170" 
HTTP/1.1 301 Moved Permanently 
Date: Sun, 30 Mar 2014 20:50:00 GMT 
Server: Apache 
Location: http://www.nice.com/careers?category=170 

所以更新你的代码,使用www.nice.com域。

此外,还可以实现逻辑遵循重定向,像这样的回答:

https://stackoverflow.com/a/6934503/25398