如何从html页面获取xPath(WebView)

时间:2017-02-28 11:31:38

标签: java android xpath

如何确定html页面上元素的XPATH,通过onTouch事件在CrossWalkView(WebView)中打开?

2 个答案:

答案 0 :(得分:0)

在webview组件上设置WebViewClient。

 browser = (WebView) findViewById(R.id.browser);
 browser.setWebViewClient(new InnerWebViewClient());

然后扩展WebViewClient类

private class InnerWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return super.shouldOverrideUrlLoading(view, url);
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);  
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

    }
}

在这里,您将获得字符串格式的url。  Webivew的onTouch事件将首先执行onPageStarted()方法。所以你会在那里获得你的Path url。

答案 1 :(得分:0)

使用JS解决了问题。 JS解决方案我来到这里: I'm storing click coordinates in my db and then reloading them later and showing them on the site where the click happened, how do I make sure it loads in the same place?

InputStream is = getResources().openRawResource(R.raw.get_xpath);
                Scanner s = new Scanner(is).useDelimiter("\\A");
                String javascript = s.hasNext() ? s.next() : "";
                myWebView.evaluateJavascript(javascript, null);

这是我的JS代码:

document.onclick= function(event) {
    if (event===undefined) event= window.event;                     // IE hack
    var target= 'target' in event? event.target : event.srcElement; // another IE hack

    var root= document.compatMode==='CSS1Compat'? document.documentElement : document.body;
    var mxy= [event.clientX+root.scrollLeft, event.clientY+root.scrollTop];

    var path= getPathTo(target);
    var txy= getPageXY(target);
    alert('Clicked element '+path+' offset '+(mxy[0]-txy[0])+', '+(mxy[1]-txy[1]));
}

function getPathTo(element) {
    if (element.id!=='')
        return 'id("'+element.id+'")';
    if (element===document.body)
        return element.tagName;

    var ix= 0;
    var siblings= element.parentNode.childNodes;
    for (var i= 0; i<siblings.length; i++) {
        var sibling= siblings[i];
        if (sibling===element)
            return getPathTo(element.parentNode)+'/'+element.tagName+'['+(ix+1)+']';
        if (sibling.nodeType===1 && sibling.tagName===element.tagName)
            ix++;
    }
}

function getPageXY(element) {
    var x= 0, y= 0;
    while (element) {
        x+= element.offsetLeft;
        y+= element.offsetTop;
        element= element.offsetParent;
    }
    return [x, y];
}