how to use htmlunit the get "next page" on google - htmlunit

I use the code below to fetch the first two pages of google search results
but i can only fetch the first page(when search page 2, it is the same with page 1)
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
/**
* A simple Google search test using HtmlUnit.
*
* #author Rahul Poonekar
* #since Apr 18, 2010
*/
public class Author_search {
static final WebClient browser;
static {
browser = new WebClient();
browser.setJavaScriptEnabled(false);
}
public static void main(String[] arguments) {
searchTest();
}
private static void searchTest() {
HtmlPage currentPage = null;
try {
currentPage = (HtmlPage) browser.getPage("http://www.google.com");
} catch (Exception e) {
System.out.println("Could not open browser window");
e.printStackTrace();
}
System.out.println("Simulated browser opened.");
try {
((HtmlTextInput) currentPage.getElementByName("q")).setValueAttribute("xxoo");
currentPage = currentPage.getElementByName("btnG").click();
System.out.println("contents: " + currentPage.asText());
HtmlElement next = (HtmlElement)currentPage.getByXPath("//span[contains(text(), 'Next')]").get(0);
currentPage = next.click();
System.out.println("contents: " + currentPage.asText());
} catch (Exception e) {
System.out.println("Could not search");
e.printStackTrace();
}
}
}
can anybody tell me how to fix this?
by the way:
How to change the language settings in google using htmlunit? any
convenient ways?
Does htmlunit treat the html like "firebug" in
firefox, or just treat it like the texts in "file->save".In my
opinion, I believe it treat it like it was a explorer, am i right?

I replaced:
HtmlElement next = (HtmlElement)currentPage.getByXPath("//span[contains(text(),'Next')]").get(0);
currentPage = next.click();
with:
HtmlAnchor nextAnchor =currentPage.getAnchorByText("Next");
currentPage = nextAnchor.click();

Related

Having an issue with Wait till element present functionality in Selenium Web driver 2.44.0

I am facing an issue with random behaviour for element wait/present/clickable. I have used below logic to wait for that element but its working some times and does not working some other times. Can some one please help me how to solve this issue with generic/standard way of element wait.
Issue/Requirement : I have to wait for an element till its present/clickable while loading web page. I am using Selenium Web driver 2.44.0 and Firefox 33.0.3
Logic used :
package com.ericsson.testing.automation.framework.ui.common;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.google.common.base.Function;
public class Test {
public static WebDriver driver;
public static long timeOut = 180000;
/** The poll time. */
public int pollTime = 100;
public void isElementClickable(WebDriver driver, WebElement webelement,
long timeOutForEachElement) {
try {
WebDriverWait wait = new WebDriverWait(driver,
timeOutForEachElement);
wait.until(ExpectedConditions.elementToBeClickable(webelement));
} catch (UnhandledAlertException ex) {
// Some debug logging info
}
}
// Senario 2
public void waitTillElementPresent(WebElement webelement) {
System.out.println("Before Fluent Wait");
System.out.println("Xpath = " + webelement);
FluentWait<WebElement> fluentWait = new FluentWait<WebElement>(
webelement);
fluentWait.pollingEvery(pollTime, TimeUnit.MILLISECONDS);
fluentWait.withTimeout(timeOut, TimeUnit.MILLISECONDS);
System.out.println("After Fluent Wait");
fluentWait.until(new Function<WebElement, Boolean>() {
public Boolean apply(WebElement webelement) {
try {
System.out.println("inside isDisplayed check");
return webelement.isDisplayed();
} catch (NoSuchElementException ex) {
System.out.println("Inside NoSuchElementException");
return false;
} catch (ElementNotVisibleException ex) {
System.out.println("Inside ElementNotVisibleException");
return false;
} catch (StaleElementReferenceException ex) {
System.out.println("Inside StaleElementRefException");
return false;
} catch (UnhandledAlertException ex) {
System.out.println("Inside UnhandledAlertException");
// Some logic for debug logging
return false;
}
}
});
}
// Senario 3
public void clickOnElement(String element) {
while (true) {
driver.findElement(By.xpath(element)).click();
System.out.println("Trying to click on element" + element);
break;
}
System.out.println("Clicked on element" + element);
}
/*
* private boolean isElementPresent(String element) {
*                  int myLink
*  =driver.findElements(By.xpath(element)).size();
*                  if (myLink != 0)                      return true;
*                  else                      return false;              }
*/
// Senario 4
public void waitTillElementisClicked(String element) {
boolean flag = true;
while (flag == true) {
// driver.findElement(By.xpath(element)).click();
// flag=driver.findElement(By.xpath(element)).isSelected();
driver.findElement(By.xpath(element)).click();
// driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
if (driver.findElement(By.xpath(element)).isSelected()) {
flag = false;
System.out.println("element already clicked");
}
// driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
System.out.println("trying to click the element");
}
System.out.println("Clicking the element");
}
}
try "driver.findElement(By.xpath(element)).size()>0". With my experience if you are doing everything correct still facing element issue, this works.
Though the size() works for webelements, you could pass your single element in the locator
wait.until(new ExpectedCondition<Boolean>()
{
public Boolean apply(WebDriver webDriver)
{
return verifyWebElementListIsPresent(se.driver().findElements(locator));
}
});
public boolean verifyWebElementListIsPresent(List<WebElement> element)
{
List<WebElement> adminPermissions = element;
if (adminPermissions.size() > 0)
{
System.out.println("Element is displayed on the page");
return true;
}
else
{
System.out.println("Element is not displayed on the page");
return false;
}
}
public static WebElement elementExists(String xpath){
// make sure driver is available to this method..
WebDriverWait wait = new WebDriverWait(driver, 2); //Increase wait time if required
try {
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
System.out.println("Element having xpath - "+xpath+" is present!");
return driver.findElement(By.xpath(xpath));
}catch(ElementNotFoundException e1){
System.out.println("Element having xpath - "+xpath+" is not present!");
return null;
} catch (TimeoutException e) {
System.out.println("Element having xpath - "+xpath+" is not present!");
return null;
}
}
WebElement xyz = elementExists(pass xpath string);
If web element is found, it will return web element, else it will return null.
If web element is present also check whether its displayed for use.
webelement.isDisplayed() should return true.

Windows Phone 7 Navigation

I am having a problem with navigating between a MainPage and a details Page.
On the main page the code looks like this:
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
State.Clear();
List<Level> lst = new List<Level>();
using (SqliteCommand selectCmd = Constants.conn.CreateCommand())
{
Constants.conn.Open();
selectCmd.Transaction = Constants.conn.BeginTransaction();
selectCmd.CommandText = " SELECT * FROM Levels";
using (SqliteDataReader reader = selectCmd.ExecuteReader())
{
while (reader.Read())
{
Level lev = new Level();
lev.ID = Convert.ToInt32(reader.GetValue(0));
lev.Name = reader.GetValue(1).ToString();
lev.levelScore = Convert.ToInt32(reader.GetValue(2));
lst.Add(lev);
}
}
selectCmd.Transaction.Connection.Close();
}
Constants.conn.Close();
levelList.ItemsSource = lst;
}
It sets the items on the page. I navigate on the detail page.
The problem comes when I navigate back to the MainPage... Although the State is Clear and the levelItems is 0 It renders The previous view of the page and when it tries to access the sqlConnection throwsan exception.

Load Image from Image URL taking so much time to display

I used the code from the following link: Signare's Blog. I have 10 image URLs and would like to retrieve and show them on my screen. When I use the code from the above link, it's taking more than 10 minutes to load all of the images. How do I speed up this loading?
URLBitmapField post_img= new URLBitmapField(image_url);
add(post_img);
where the class URLBitmapField is defined as:
import net.rim.device.api.math.Fixed32;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
public class URLBitmapField extends BitmapField implements URLDataCallback {
EncodedImage result = null;
public static EncodedImage _encoded_img = null;
int _imgWidth = 52;
int _imgHeight = 62;
int _imgMargin = 10;
public URLBitmapField(String url) {
try {
http_image_data_extrator.getWebData(url, this);
}
catch (Exception e) {}
}
public Bitmap getBitmap() {
if (_encoded_img == null) return null;
return _encoded_img.getBitmap();
}
public void callback(final String data) {
if (data.startsWith("Exception")) return;
try {
byte[] dataArray = data.getBytes();
_encoded_img = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length); // with scale
_encoded_img = sizeImage(_encoded_img, _imgWidth, _imgHeight);
setImage(_encoded_img);
UiApplication.getUiApplication().getActiveScreen().invalidate();
}
catch (final Exception e){}
}
public EncodedImage sizeImage(EncodedImage image, int width, int height) {
int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
int currentHeightFixed32 = Fixed32.toFP(image.getHeight());
int requiredWidthFixed32 = Fixed32.toFP(width);
int requiredHeightFixed32 = Fixed32.toFP(height);
int scaleXFixed32 = Fixed32.div(currentWidthFixed32,requiredWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32,requiredHeightFixed32);
result = image.scaleImage32(scaleXFixed32, scaleYFixed32);
return result;
}
}
public interface URLDataCallback {
public void callback(String data);
}
and the class http_image_data_extrator is defined as:
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.system.WLANInfo;
import net.rim.device.api.ui.UiApplication;
public class http_image_data_extrator {
static String url_="";
static StringBuffer rawResponse=null;
public static void getWebData(String url, final URLDataCallback callback) throws IOException {
HttpConnection connection = null;
InputStream inputStream = null;
try {
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)&& RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
url += ";interface=wifi";
}
connection = (HttpConnection) Connector.open(url, Connector.READ, true);
String location=connection.getHeaderField("location");
if(location!=null){
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)&& RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
location += ";interface=wifi";
}
connection = (HttpConnection) Connector.open(location, Connector.READ, true);
}else{
connection = (HttpConnection) Connector.open(url, Connector.READ, true);
}
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK){
throw new IOException("HTTP response code: "+ responseCode);
}
final String result = rawResponse.toString();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run(){
callback.callback(result);
}
});
}
catch (final Exception ex) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
callback.callback("Exception (" + ex.getClass() + "): " + ex.getMessage());
}
});
}
}
}
Resize on the server
Resizing the images on the server is the best answer. Because downloading big images and scaling them down requires a lot of everything (network, memory, cpu) on the device.
Resize via a proxy
If the image server is not under your control, you could still use your own server as a resizing proxy (send the image url and desired size to your server, it gets the image, resizes, and returns the resized image). Maybe there is a service that does this already.
Cheaper decode option
Some decode options may make decoding (and resizing) cheaper. DECODE_NO_DITHER, DECODE_READONLY, and DECODE_NATIVE all seem worth trying.
http://www.blackberry.com/developers/docs/4.2api/net/rim/device/api/system/EncodedImage.html#DECODE_NO_DITHER
Serial instead of parallel
You mentioned you are loading 10 images. If 10 images takes more than 10x the time 1 image takes, then the system might be "thrashing". Like it might initiate all 10 requests, then wind up working on 10 fullscale images in memory at the same time in callbacks. Could try showing the first image before starting to download the next, which also gives the user something to look at sooner. Similarly, calling invalidate 10 times in parallel (in the callback) might cause a hiccup.

Htmlunit mouseOver() does not trigger popup

I wrote the following test. It looks like the htmlunit mouseOver() function is not working (I don't see the html code of the popover).
Am I missing something? How can I solve this issue?
#Test
public void test() throws Exception {
try {
WebClient client = new WebClient(BrowserVersion.FIREFOX_3_6);
HtmlPage currentPage = client.getPage("http://plugins.learningjquery.com/cluetip/demo/");
String xpath = "//a[#title='jTip Style!']";
HtmlElement elm = (HtmlElement) currentPage.getByXPath(xpath).get(0);
xpath = "(//img[#src='kids-drop-sand.jpg'])[1]";
HtmlPage newPage = (HtmlPage) elm.mouseOver();
Assert.assertTrue(newPage.getByXPath(xpath).size() > 0, "Popover is not displayed");
} catch (Exception ex) {
logger.error("Exception thrown in " + this.getClass().toString()
+ " " + ex.getMessage(), ex);
throw ex;
}
}
Did you try with the latest svn ?
http://htmlunit.sourceforge.net/gettingLatestCode.html
Or with the last successed build : http://build.canoo.com/htmlunit/buildresults?log=log20120530150012Lbuild.1963
The latest release available is quite old and manage poorly JS events.

Windows Phone app throws exception (quit automatically) when running under 3G, but fine with WIFI. Very weird

I have tried hundreds of times to find errors for this piece of codes.
It only works through WIFI, but When I switch off WIFI on my phone, and run the app again, this app just shut down automatically, which means it thrown an exception.
The app is simple, I used WebClint() to download HTML source and parsed it with HTML Agility Pack, then added them to a list, foreach the list to creat each news object.
I have tried catch the exception stacktrace and bind it to a texblock, It said some of ArgumentOutOfRange exception and Genericlist(int32 index)???
I have no idea about it, It was fine in wifi, but not in 3G network. Can anyone help?
public partial class MainPage : PhoneApplicationPage
{
string srcHTML;
HtmlNode UrlNode;
ObservableCollection<News> newsList = new ObservableCollection<News>();
List<HtmlNode> headlines;
HtmlDocument hd;
News n;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient webClenet = new WebClient();
webClenet.Encoding = new HtmlAgilityPack.Gb2312Encoding();
webClenet.DownloadStringAsync(new Uri("http://www.6park.com/news/multi1.shtml", UriKind.RelativeOrAbsolute));
webClenet.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClenet_DownloadStringCompleted);
}
private void webClenet_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
srcHTML = e.Result;
GetHeadlinePage(srcHTML);
}
private void GetHeadlinePage(string srcHTML)
{
hd = new HtmlDocument();
hd.LoadHtml(srcHTML);
try
{
UrlNode = hd.DocumentNode.ChildNodes[1].ChildNodes[3].ChildNodes[8].ChildNodes["tr"].ChildNodes["td"].ChildNodes["ul"];
headlines = UrlNode.Descendants("a").ToList();
foreach (var headline in headlines)
{
if (headline.Attributes["href"].Value.Contains("6park"))
{
n = new News();
n.NewsTitle = headline.InnerText;
n.NewsUrl = headline.Attributes["href"].Value;
n.NewsDetails = headline.NextSibling.InnerText.Replace("- ", "新闻来源:") + headline.NextSibling.NextSibling.InnerText + headline.NextSibling.NextSibling.NextSibling.InnerText;
newsList.Add(n);
}
}
}
catch (Exception ex)
{
//NewsSource.Text = ex.StackTrace + "\n" + ex.Message;
}
NewslistBox.ItemsSource = newsList;
//NewsHeadlineWebBrowser.NavigateToString(ConvertExtendedASCII(headNews));
}
}
I'd debug the value passed to GetHeadlinePage().
I'd suspect that the response is different based on the network or the request is timing out or you're getting some other error.
I'd assume that the call to LoadHtml() is failing as this isn't inside any exception handling/trapping and you've not validating the value passed to it.

Resources