本文介绍了在java中执行javascript - 打开一个URL并获取链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
public class Main {
public static void main(String [] args){
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName(js);
尝试{
FileReader reader = new FileReader(C:/yourfile.js);
engine.put(urlfromjava,http://www.something.com/?asvb);
engine.eval(reader);
reader.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
现在,yourfile。 js包含此行
函数urlget(url)
{
print(URL:+ url );
var loc = window.open(url);
var link = document.getElementsByTagName('a')[61]。href;
return(\\\
Link is:\\\
+ link);
}
var x = urlget(urlfromjava);
print(x);
我收到错误
javax.script.ScriptException:sun.org.mozilla.javascript.internal.EcmaError:ReferenceError:windowis not defined
如何打开一个URL并从java中获取链接?
解决方案
根据:
由于您没有执行你的脚本在浏览器中,窗口对象没有被定义。
您可以使用URL / URLConnecion类读取URL并将其提供给ScriptEngine。 。
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
public class Main {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
try {
FileReader reader = new FileReader("C:/yourfile.js");
engine.put("urlfromjava", "http://www.something.com/?asvb");
engine.eval(reader);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Right now, the yourfile.js contains this line
function urlget(url)
{
print("URL:"+url);
var loc = window.open(url);
var link = document.getElementsByTagName('a')["61"].href;
return ("\nLink is: \n"+link);
}
var x = urlget(urlfromjava);
print(x);
I get the error
"javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "window" is not defined"
How to open a URL and get the links of it from java?
解决方案
According to the documentation:
Since you are not executing your script in a browser, the window object is not defined.
You can read the URL using the URL/URLConnecion classes and feed it to the ScriptEngine. There is a tutorial here.
这篇关于在java中执行javascript - 打开一个URL并获取链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!