Search code examples
javaandroidseleniumautomationappium

How to get the android.webkit.WebView contents as a String using Appium


I would like to know how to get the contents of a WebView as a String using Appium. I am using the Android driver.

I have tried the following code:

androidDriver.getPageSource();

But it gives only a xml.

<?xml version="1.0" encoding="UTF-8"?><hierarchy rotation="0"><android.widget.FrameLayout index="0" text="" class="android.widget.FrameLayout" package="com.test.program" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[0,0][768,1184]" resource-id="" instance="0"><android.widget.LinearLayout index="0" text="" class="android.widget.LinearLayout" package="com.test.program" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" bounds="[0,0][768,1184]" resource-id="" instance="0"><android.widget.FrameLayout index="0" text="" class="android.widget.FrameLayout" .......... resource-id="android:id/navigationBarBackground" instance="201"/></android.widget.FrameLayout></hierarchy>

Solution

  • I have found the solution for this.

    public final String WEBVIEW = "WEBVIEW_com.maxsoft.poker";
    public final String NATIVE_APP = "NATIVE_APP";
    
    
    public String getHTMLPageSource(String url){
        switchContextTo(WEBVIEW);
        getDriver().navigate().to(url);
        return getDriver().getPageSource();
    }
    
    public void switchContextTo(String context){
        if (context.toLowerCase().equals(WEBVIEW.toLowerCase())) {
            getDriver().context(WEBVIEW); // set context to WEBVIEW_1
        } else {
            getDriver().context(NATIVE_APP); // set context to NATIVE_APP
        }
    }
    

    The problem was I didn't switch the context from native app to webview. So that getPageSource() will return the xml content which is relevant to the current activity. So from switchContextTo(String context) method I switch the current context from native app to webview and from getHTMLPageSource(String url) I am getting the webview content as a String