admin
2021-04-24 77e706cca33c97a4428879cc9a6f98aae085c142
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.yeshi.buwan.util.crawler;
 
import com.google.gson.Gson;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
 
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.IOException;
 
public class JsoupJavasciptUtil {
 
    /**
     * 获取脚本中的内容
     *
     * @param url
     * @param userAgent
     * @param key
     * @return
     * @throws IOException
     */
    public static String getScriptContent(String url, String userAgent, String key) throws IOException {
        String script = null;
        Connection connection = Jsoup.connect(url).timeout(10000);
        if (userAgent != null)
            connection.userAgent(userAgent);
        Document doc = connection.get();
        Elements els = doc.getElementsByTag("script");
        for (int i = 0; i < els.size(); i++) {
            if (els.get(i).html().indexOf(key) > -1) {
                script = els.get(i).html();
                break;
            }
        }
        return script;
    }
 
    private static ScriptEngineManager manager = new ScriptEngineManager();
    private static ScriptEngine jsEngine = manager.getEngineByName("javascript");
 
 
    /**
     * 执行javascript脚本
     *
     * @param script
     * @param methodName
     * @param args
     * @return
     * @throws ScriptException
     * @throws NoSuchMethodException
     */
    public static Object executeJavascript(String script, String methodName, Object... args) throws ScriptException, NoSuchMethodException {
        try {
            jsEngine.eval(script);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
 
        if (jsEngine instanceof Invocable) {
            Invocable in = (Invocable) jsEngine;
            Object result = in.invokeFunction(methodName, args);
            return result;
        }
        return null;
    }
 
}