Javascript PhantomJS 单击页面上的链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13536752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PhantomJS click a link on a page
提问by mikkeljuhl
I have written some parts of a PhantomJS application. I am parsing on a website where I am writing username and password to a formular. After this I have to click on a link. Whereas I get this error:
我已经编写了 PhantomJS 应用程序的某些部分。我正在解析一个网站,在那里我将用户名和密码写入公式。在此之后,我必须单击一个链接。而我收到此错误:
TypeError: 'undefined' is not a function (evaluating 'myLink.click()')
phantomjs://webpage.evaluate():11
phantomjs://webpage.evaluate():22
phantomjs://webpage.evaluate():22
This is my PhantomJS code:
这是我的 PhantomJS 代码:
if(document.getElementById("m_Content_submitbtn2").getAttribute('data-role') == "button"){
var myLink = document.getElementById("m_Content_submitbtn2");
myLink.click();
}
And this is my link:
这是我的链接:
<div class='button'><a href="#" data-role="button" tabindex='0' onclick='WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("m$Content$submitbtn2", "", true, "", "", false, true)); return false;' id="m_Content_submitbtn2">Log ind</a></div>
回答by Martijn Hols
You are attempting to use the click()method on an <a>element which is not supported in all browser by default. Instead try using something like thiswhere instead of myLink.click();you will have to do eventFire(myLink, 'click');.
您正在尝试在所有浏览器默认不支持click()的<a>元素上使用该方法。相反,尝试使用类似这种地方,而不是myLink.click();你将不得不这样做eventFire(myLink, 'click');。
回答by two7s_clash
Or include jQuery and do something like:
或者包含 jQuery 并执行以下操作:
var page = require('webpage').create();
page.open('http://www.sample.com', function() {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
$("button").click();
});
phantom.exit()
});
});

