如果没有具有特定内容的iframe元素,则recaptcha不会显示在phantomjs中

时间:2014-10-28 16:18:54

标签: javascript web-scraping phantomjs recaptcha

我正在尝试使用phantomjs使用recaptcha小部件抓取一个页面,但是当我得到页面时它没有验证码图像。

如果我向页面添加iframe元素,则会显示图像。最奇怪的是,只有在制作具有特定内容的iframe时才会显示图片。

以下是我用来测试的html代码(这是来自带有iframe元素的recaptcha文档的常规代码)

<form action="" method="post">
    <script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=6LfUUtMSAAAAAOBuPTWtMAnAu3l9AS-iHZb6iFpp&amp;error=">
    </script>
    <noscript>
        <iframe src="http://www.google.com/recaptcha/api/noscript?k=6LfUUtMSAAAAAOBuPTWtMAnAu3l9AS-iHZb6iFpp&amp;error=" height="300" width="500" frameborder="0"></iframe>
        <br>
        <textarea name="recaptcha_challenge_field" rows="3" cols="40">
        </textarea>
        <input type="hidden" name="recaptcha_response_field" value="manual_challenge">
    </noscript>
</form>
<iframe src="frame.html"></iframe>

iframe是指页面frame.html,这里是它的“特定代码”

<a><img src='http://c'></a>

如果您尝试稍微更改frame.html的内容,则可能无法获取验证码图片。

我使用的PhantomJS脚本是:

var url = 'http://127.0.0.1/php_api/recaptcha.html';
var page = require('webpage').create();
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0';
page.open(url, function (status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        var p = page.evaluate(function () {
            return document.getElementById("recaptcha_challenge_image").src;
        });
        console.log(p);
    }
    phantom.exit();
});

这是我第一次使用PhantomJS,那么我有什么遗漏吗?

1 个答案:

答案 0 :(得分:2)

这与您网页上的其他iframe无关。调用page.open回调时,不会加载重新访问脚本。它还没有创建reCaptcha表,也没有加载验证码图像。这是一个时间问题。

您可以使用setTimeout等静态时间或使用waitFor等待图片出现。

page.open(url, function (status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        setTimeout(function(){
            var p = page.evaluate(function () {
                return document.getElementById("recaptcha_challenge_image").src;
            });
            console.log(p);
            phantom.exit();
        }, 5000);
    }
});

不要忘记在超时后也应该调用phantom.exit,否则你只是提前退出。