Search code examples
androidimagehtmlgetelementsbytagname

Trying to get an image from div id in android studio


I honestly don't even know where the proper place to begin with this would be, so I've been fumbling around with it. I've seen several similar posts, but I haven't been able to get anything to work.

What I'd like to do is use the div id to get a specific image from a web site without having to hard code the image link in. For instance, one of the things I'm trying to do this for is a webcomic. I'd like to be able to use the div id="comic-1" tag and get the img src="..." it's connected to.

I'm very open to methods of doing this. Here's what I tried most recently:

wView.loadUrl("...");
wView.getSettings().setJavaScriptEnabled(true);
wView.getSettings().setLoadWithOverviewMode(true);
wView.getSettings().setUseWideViewPort(true);
wView.getSettings().setSupportZoom(true);
wView.getSettings().setBuiltInZoomControls(true);
wView.setWebViewClient(new WebViewClient(){

@Override
public void onPageFinished (WebView webView, String url)
{
    webView.loadUrl("javascript:document.getElementById('comic-1').src;");
}

But it doesn't load the image. It just loads the site, as normal.

Also, it's a bit of an off-shoot, but I'm trying to figure out how to use these tags in general. Another thing I'd like to do is delete something within a tag. Here's what I've tried for that:

webView.loadUrl("javascript:(function() { " +
                "document.getElementsByTagName('header')[0].style.display=\"none\"; " +
                "})()");

I should've included the HTML block I was working with. I don't have an image id to work with, unfortunately.

<div id="comic-1" class="comicpane"><a href="" title="..."><img src="..." alt="..." title="..."/></a></div> 

Solution

  • You can try this:

    HTML block:

    <div id="comic-1">
         <img id="image" src="http://www.w3schools.com/jsref/compman.gif" width="107" height="98">
         <img id="smile" src="http://www.w3schools.com/tags/smiley.gif" width="107" height="98">
    </div>
    

    Accessing it:

    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(URL);
    webView.setWebViewClient(new WebViewClient(){
        @Override
        public void onPageFinished(WebView webView, String url)
        {
            webView.loadUrl("javascript:var s = document.getElementById('smile').src;document.write(s);");
        }
    });
    

    Going by the example shown above, this will write the image source in the document.

    [EDIT]

    var parent = document.getElementById("comic-1");
    var child = parent.getElementsByTagName("img");
    document.write(" image 1 = " + child[0].src + " image 2 = " + child[1].src);