2013-03-20 95 views
0

我有一个应用程序正在抓取数据的网站。它是在iFrame中抓取网站。我需要从相同的iframe中抓取后续网站,这两个网站都有一个条目地址,这个条目导致带有一个字段和一个按钮的页面。在该页面上,我在该字段中输入一个数字,然后按下按钮进入下一页。我遇到的问题是,当我(编码)按下按钮时,它不会等待页面加载并在有任何声音之前进行擦除。JS异步/加载行为

setTimeOutDelay似乎完全被忽略。

$(document).ready(function() { 

    $('#startbutton').click(function() { 
    $('#iframe').attr('src', 'www.pageone.com'); 
    // Here I start a load because I need to wait for the button to become available. 
    $('#iframe').one('load', function() { 
     $('#okbutton').click(); 
    }); 
    // This is where it goes wrong. I would assume that it waits for the second page 
    // to load. But it doesn't. Adding another load block didn't help. 
    scrapeFunction(); 
    }); 

}); 

我该如何获得这些时机?

+0

您是不是指'on'而不是'one'? – 2013-03-20 16:48:29

+0

@VivinPaliath我假设他只希望它运行一次。 – Archer 2013-03-20 16:53:03

+0

我的意思是一个,因为否则的话,负载继续点燃,并点击确定按钮:D – Difusio 2013-03-20 17:10:46

回答

1

当我(编码)按下按钮,它不会等待页面加载和擦伤前居然还有anythong有

,它甚至不等待要按下的按钮。相反,您想等待另一个负载事件:

var $if = $('#iframe'); 
// (1) assign a load handler 
$if.one('load', function() { // that says "When loaded (first), … 
    // (3) assign the next load handler 
    $if.one('load', function() { 
     // (5) which then (second load) can scrape the content 
     scrapefunction(); 
    }); 
    // (4) and load it 
    $('#okbutton').click(); 
}); // …" 
// (2) and load it 
$('#iframe').attr('src', 'www.pageone.com'); 
+0

王牌,我得到它的工作!你有没有可能澄清为什么它按这个顺序运行一点?然后我可以真正理解它。如果没有,谢谢! – Difusio 2013-03-21 13:14:24

+0

我希望我能改善它。数字表示异步调用的处理程序的执行顺序 – Bergi 2013-03-21 13:58:02

0

这将执行加载iFrame时的代码。

$("iframe").ready(function() { 
    //iFrame loaded 
    scrapeFunction(); 
});​ 
+0

除了当前的代码或作为替换,我还可以在哪里添加? – Difusio 2013-03-20 17:11:11

+0

将scrapeFunction()函数包含在其中,直到iFrame加载了所有DOM元素后才会执行该函数。 – Greg 2013-03-20 17:14:54

+0

这不行。我在scrapeFunction中有一个提醒,看看它何时被调用,我可以看到它在页面加载之前被调用。我正在做两个后续加载,一个用于初始页面,然后是另一个加载到需要被刮掉的页面。 – Difusio 2013-03-21 10:38:11