jeudi 20 juillet 2017

Java - HTMLUnit for submitting/search algorithm

spoiler: desperation incoming I am trying to use the HTMLUnit API to connect to 'https://www.ebay.com/', then I want to insert the string 'toys' to the search box (name: '_nkw'), then submit the search using the search button (id: gh-btn), then select the 'sold items' checkbox (id: 'w_1500584247380_cbx') and finally, get the first result list element (first result set, id: w3-items[0]) and extract its price.

I've been testing around using Google to print div box after submitting a search, however, I cannot seem to connect to ebay.com.

My (old, functional) Google code:

final WebClient webClient = new WebClient();

    HtmlPage page1 = webClient.getPage("http://www.google.com");
    HtmlInput input1 = page1.getElementByName("q");
    input1.setValueAttribute("yarn");

    HtmlSubmitInput submit1 = page1.getElementByName("btnK");

    page1=submit1.click();

    System.out.println(page1.getWebResponse().getContentAsString()); 

My (new, not functional) eBay code:

package application;

import java.io.IOException;
import java.net.*;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.javascript.host.html.HTMLListElement;

public class EbayBackend {

    public String connect() throws IOException{


         final WebClient webClient = new WebClient();

            HtmlPage page1 = webClient.getPage("https://www.ebay.com/");    
            //connection to eBay.com

            HtmlInput input1 = page1.getElementByName("_nkw");  
           //get edit field
            input1.setValueAttribute("toys");   //insert 'toys'

            page1.getElementById("gh-btn").click(); //submitts search

            page1.getElementById("w_1500585028108_cbx").click();    
            //select submit button

            return page1.getElementById("w3-items[0]").asText();    
            //is meant to print whole <li> element, but no results shown

    }

}




Aucun commentaire:

Enregistrer un commentaire