【问题标题】:jQuery, ajax, and php web scraper acting strangelyjQuery、ajax 和 php 网络爬虫行为异常
【发布时间】:2015-01-04 19:46:25
【问题描述】:

我正在尝试抓取网页,但在我的浏览器控制台中得到了一些奇怪的结果(如下所示)。这是我的代码:

index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Icefilms Searcher</title>
    <script type="text/javascript" src="jquery-2.0.3.min.js"></script>
</head>

<body>
    <script type="text/javascript" src="script.js"></script>
    <div id="container" style="width:1100px;position:relative;"></div>
</body>
</html>

script.js

$(document).ready(function(){

var currNum = 168000;
var maxNum =  168005;

function generateNextUrl(){
    currNum++;
    return currNum-1;
}

scrapeThis(generateNextUrl());

function scrapeThis(theUrl){
    $.ajax({
        url:
            "php.php",
        data:
            "icefilmsURL=" + theUrl,
        success:
            function(response){
                var movieTitle = $(response).find("#videotitle").find("span:first").text();
                $("#container").append("<a href='http://www.icefilms.info/ip.php?v="+theUrl+"' target='blank'>"+movieTitle+"</a><br>");
            },
        complete:
            function(){
                if(currNum < maxNum+1){
                    scrapeThis(generateNextUrl());
                }
            },
        error:
            function(xhr,err){
                $("#container").append("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
                $("#container").append("responseText: "+xhr.responseText);
            }
    });
};
});

php.php

<?php
    echo file_get_contents("http://www.icefilms.info/ip.php?v=".$_GET["icefilmsURL"]);
?>

代码运行良好,但这是我在控制台中看到的:

有什么想法吗?

【问题讨论】:

    标签: javascript php jquery ajax web-scraping


    【解决方案1】:

    您在控制台中看到这些是因为您正在抓取的页面包含对相对路径的引用。

    也就是说而不是

    <img src="http://www.icefilms.info/someimage.jpg">
    

    代码是

    <img src="someimage.jpg">
    

    因此,当您在自己的域中抓取并显示其 HTML 时,浏览器会尝试从您的域(在本例中为 localhost)加载图像。但是您的服务器上没有该图像。

    您可以在 HTML 中使用基本 href 来解决此问题,或者您可以查找并替换相对路径图像以包含域。

    <base href="http://www.icefilms.info/">
    

    【讨论】:

    • 好吧,我就是这么想的。我通过preg_replace-ing 删除了来自file_get_contents 的任何“src”标签的错误。但这对我来说仍然没有意义,因为我没有执行/解析任何代码,我只是在筛选它以查找文本。在我的代码中的哪一点是浏览器决定执行和搜索图像?
    • 您在出错时输出 responseText - 可能您遇到了错误?
    • 有人对此有任何反馈吗?
    猜你喜欢
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 2011-12-11
    相关资源
    最近更新 更多