【问题标题】:What prevents me from using $.ajax to load another domain's html?是什么阻止我使用 $.ajax 加载另一个域的 html?
【发布时间】:2012-01-20 16:30:22
【问题描述】:

我的域名:

<!DOCTYPE html>  
<html>
<head>
<title>scrape</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
    <script>
        $.ajax({url:'http://their-domain.com/index.html',
        dataType:'html',
            success:function(data){console.log(data);}
        });
    </script>
</body>
</html>

是什么阻止我抓取他们的域名?有什么解决办法吗?

附录:感谢大家对使用服务器端脚本的建议,但我目前有兴趣专门使用客户端解决这个问题。

如果我使用“jsonp”格式化请求,我至少会得到响应,但会出现以下错误:“Uncaught SyntaxError: Unexpected token

<!DOCTYPE html>  
<html>
<head>
<title>scrape</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
    <script>
        $.ajax({url:'http://their-domain.com/index.html',
        dataType:'jsonp',
            success:function(data){console.log(data);}
        });
    </script>
</body>
</html>

【问题讨论】:

标签: jquery html ajax screen-scraping web-scraping


【解决方案1】:

有四种方法可以绕过Same Origin Policy

  1. 代理 - 您从您的服务器请求它,您的服务器从其他域请求它,您的服务器将它返回给浏览器
  2. Flash cross domain policy - 其他域必须将 crossdomain.xml 文件添加到他们的站点
  3. Cross domain HTTP header - 其他域必须在其页面中添加 Access-Control-Allow-Origin 标头
  4. JSONP - 这是一个提供回调函数的 json 网络服务。其他域必须实现这一点。

注意:在没有其他域帮助的情况下,唯一方法是#1,通过您自己的服务器路由。

【讨论】:

    【解决方案2】:

    Same Origin Policy 阻止客户端脚本从不是来自请求发起者的域中获取数据。您需要一个服务器端脚本来充当代理

    【讨论】:

      【解决方案3】:

      这是同源策略,它可以防止跨域请求。如果你想抓取 html,你最好编写一个服务器端进程来获取内容,然后使用 ajax 向你的服务器发出请求,其中包含收集到的数据。

      【讨论】:

        【解决方案4】:

        一种解决方法是制作一个服务器端脚本(例如 PHP)来获取页面,并让 $.ajax 调用它。

        【讨论】:

          猜你喜欢
          • 2017-11-16
          • 1970-01-01
          • 2020-06-09
          • 2015-04-24
          • 2013-10-24
          • 1970-01-01
          • 2020-05-03
          • 2010-10-24
          • 2020-11-05
          相关资源
          最近更新 更多