简体   繁体   English

如何使用phantomjs在JS事件后获取更新的页面内容?

[英]How to get updated page content after a JS event using phantomjs?

I have a page with a simple form. 我有一个带有简单表格的页面。 This form has ONE input text. 该表格有一个输入文本。

I have this code: 我有以下代码:

page.open("http://www.example.com", function (status) {    
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js", function() {
        page.evaluate(function() {
            $('input[name=myText]').val('my content');
        });     
    });     
});

(as you can see i also loaded jquery) (如您所见,我也加载了jQuery)

Now, when i set the content of this input text, the page changes, the content of the page changes. 现在,当我设置此输入文​​本的内容时,页面会更改,页面的内容也会更改。

My question is: how can I get the updated content? 我的问题是:如何获得更新的内容? The problem is that i need to submit the form but i can not do it after: 问题是我需要提交表格,但是之后我不能这样做:

$('input[name=myText]').val('my content');

because when i set it there is an JS event on the page that changes the content. 因为当我设置它时,页面上有一个JS事件会更改内容。

SO I must read the new content, find the form using JQuery and then submit it. 因此,我必须阅读新内容,使用JQuery查找表单,然后提交。

Could someone help me? 有人可以帮我吗?

Thank you! 谢谢!

So your page.evaluate() call has a side effect and that changes the page. 因此,您的page.evaluate()调用具有副作用,并且会更改页面。 The question is whether this change occurs instantaneously. 问题是这种变化是否瞬间发生。 But you cannot assume that it does - particularly if it causes a fetch of new content from a remote webserver. 但是您不能假设它确实如此-尤其是当它导致从远程Web服务器获取新内容时。

That being the case the best thing you can try is to sleep for a while and then assume your page has the new content. 在这种情况下,您可以尝试的最好方法是休眠一段时间,然后假设您的页面包含新内容。 Or alternatively, when you feel more advanced, poll on a regular basis for a DOM object you are expecting to appear. 或者,当您感觉更高级时,请定期轮询您希望出现的DOM对象。 But the beginner should try a sleep: 但是初学者应该尝试入睡:

....
page.evaluate( function() { ... } );
window.setTimeout(
    function() {
        /* press submit button */
    },
    5000 /* wait 5 seconds (5,000ms) */
);
....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM