Proble statement is as follows:
Open www.google.com in browser.
Add selenium hq in search
findout search result for wikipedia link for selenium hq.
print description which is displayed next to link to console.
search result is sometimes appears on 1st page and sometimes not.
i am able to search on 1st page and if its not there then traverse to 2nd page and so on.
but not able to get that description.
My code is:
WebDriver driver = null;
String baseUrl = "https://www.google.com";
System.setProperty("webdriver.gecko.driver", "C:\\SeleniumDrivers\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.xpath(".//input[#class='gLFyf gsfi']")).sendKeys("Selenium HQ");
driver.findElement(By.xpath(".//input[#class='gLFyf gsfi']")).sendKeys(Keys.ENTER);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
List<WebElement> linkElements = new ArrayList<WebElement>();
ListIterator<WebElement> itr = null;
WebElement toClick = null;
int pageNumber = 1;
WebDriverWait wait = new WebDriverWait(driver, 10);
boolean flag = false;
while (!flag)
{
linkElements = wait.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By
.xpath("//h3[#class='s']")));
itr = linkElements.listIterator(); // re-initializing iterator
while (itr.hasNext())
{
toClick = itr.next();
if (toClick.getText().contains("Wikidata"))
{
String desc = toClick.getText();
System.out.println(desc);
flag = true;
break;
}
}
if (!flag)
{
driver.findElement(By.xpath("//a[#id='pnnext']/span[1]")).click();
pageNumber++;
linkElements.clear(); // clean list
// wait.until(ExpectedConditions.textToBePresentInElementLocated(
//By.xpath("//div[#class='st']"), pageNumber + ""));
}
}
driver.close();
looking for a solution to this problem..
Related
Hi Iam new to selenium,
In URL: https://jqueryui.com/sortable/ with help of Mouse We need to sort the list. I tried this code but nothing happens any workaround in selenium how we can do this?
there are 7 items we need to sort data in descending order by mouse
I tried the below code but it's not working how can I achieve it
WebDriver driver =new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://jqueryui.com/sortable/");
driver.switchTo().frame(0);
List<WebElement> lists = driver.findElements(By.xpath("//ul[#id='sortable']/li"));
Actions a = new Actions(driver);
for(int i=0;i<lists.size();++i){
WebElement element = lists.get(i);
String text = lists.get(i).getText();
String[] values = text.split(" ");
int number = Integer.valueOf(values[1]);
}
a.clickAndHold(lists.get(0)).dragAndDrop(lists.get(0), lists.get(6)).build().perform();
a.clickAndHold(lists.get(0)).moveToElement(lists.get(3)).release().build().perform();
///////////////////////////////////////////////////////////////
for(int i =dragAndDropElement.size();i>1;i--) {
WebElement element = driver.findElement(By.xpath("((//ul[#id='sortable']/li)["+i+"])"));
//Just collected all the destination location,
WebElement destination1 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[1])"));
WebElement destination2 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[2])"));
WebElement destination3 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[3])"));
WebElement destination4 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[4])"));
WebElement destination5 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[5])"));
WebElement destination6 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[6])"));
WebElement destination7 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[7])"));
Actions action = new Actions(driver);
if(element!=null) {
action.dragAndDrop(destination1,element).perform();
action.dragAndDrop(destination2,element).perform();
action.dragAndDrop(destination3,element).perform();
action.dragAndDrop(destination4,element).perform();
action.dragAndDrop(destination5,element).perform();
action.dragAndDrop(destination6,element).perform();
action.dragAndDrop(destination7,element).perform();
break;
}
You can check with this solution, Further, you could enhance this as per your requirement and simplification. Anyway, I hope it will help you.
WebDriver driver = new ChromeDriver();
driver.get("https://jqueryui.com/sortable/");
new WebDriverWait(driver,10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[#class='demo-frame']")));
List<WebElement> dragAndDropElement = driver.findElements(By.xpath("//ul[#id='sortable']/li"));
System.out.println(dragAndDropElement.size());
for(int i =1;i<dragAndDropElement.size();i++) {
WebElement element = driver.findElement(By.xpath("((//ul[#id='sortable']/li)["+i+"])"));
//Just collected all the destination location,
WebElement destination1 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[1])"));
WebElement destination2 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[2])"));
WebElement destination3 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[3])"));
WebElement destination4 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[4])"));
WebElement destination5 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[5])"));
WebElement destination6 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[6])"));
WebElement destination7 = driver.findElement(By.xpath("((//ul[#id='sortable']/li)[7])"));
Actions action = new Actions(driver);
if(element!=null) {
action.dragAndDrop(destination7,element).perform();
action.dragAndDrop(destination6,element).perform();
action.dragAndDrop(destination5,element).perform();
action.dragAndDrop(destination4,element).perform();
action.dragAndDrop(destination3,element).perform();
action.dragAndDrop(destination2,element).perform();
action.dragAndDrop(destination1,element).perform();
break;
}
}
You can try this code:
List<WebElement> lists = driver.findElements(By.xpath("//ul[#id='sortable']/li"));
// above list holds size of 7
Actions a = new Actions(driver);
WebElement lastEle = driver.findElement(By.xpath("//li[text()='Item " + lists.size() + "']"));
// I am picking last element as we have to sort in descending order. That means 1-7, 2-7, 3-7 etc..
// At last the order should be Item 7, 6, 5, 4, 3, 2, 1.
for(int i=1;i<=lists.size() - 1;++i) {
// Here, I don't want to drag last element i.e Item 7 as it will be on top at last. That is why I am not considering 7th element to drag
WebElement elementToDrag = driver.findElement(By.xpath("//li[text()='Item " + i + "']"));
a.clickAndHold(elementToDrag).dragAndDrop(elementToDrag, lastEle).build().perform();
Thread.sleep(1000);
}
When we search for mobiles on Amazon and click a particular mobile and print a particular review of the product in the console using selenium with java with cucumber framework, Its is not printing anything.
#Then("Click on the add to cart button")
public void click_on_the_add_to_cart_button() {
Set<String> ids = driver.getWindowHandles();
Iterator<String> it = ids.iterator();
String parentId = it.next();
String childId = it.next();
driver.switchTo().window(childId);
l1=new LoginPojo();
btnClick(l1.getAddToCart());
JavascriptExecutor js =(JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,10000)","");
String data = driver.findElement(By.xpath(" //[#id=\"customer_review- R1R9S770F79ZNP\"]/div[4]/span/div/div[1]/span")).getText();
System.out.println("Result: " + data);
}
See if this works. I am trying to grab the 4 element from this link
List<WebElement> reviews = driver.findElements(By.xpath("//div[#data-hook='review']"));
JavascriptExecutor js = (JavascriptExecutor)driver;
WebElement reviewEle = reviews.get(4);
js.executeScript("arguments[0].scrollIntoView(true);", reviewEle);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
System.out.println(reviewEle.findElement(By.xpath(".//div[contains(#id,'review-card')]/div[contains(#id,'customer_review')]//following-sibling::div[contains(#class,'small review-data')]//span[#data-hook='review-body']")).getText());
I am on webpage:
https://www.alibaba.com/products/MAc_book.html
Clicking the very first product with following:
element3 = (new WebDriverWait(driver, 10)).until(ExpectedConditions
.visibilityOfElementLocated(By
.xpath("//a[#data-hislog='60639615540']")));
element3 = driver.findElement(By.xpath("//a[#data-hislog='60639615540']"));
element3.click();
On the new webpage, accessing the Contact supplier button but no luck
element1 = (new WebDriverWait(driver, 20000)).until(ExpectedConditions
.presenceOfElementLocated(By
.xpath("//a[#title='Click to send an inquiry']")));
element1 = driver.findElement(By.xpath("//a[#title='Click to send an inquiry']"));
used following code smipets as well, but still couldn't
>driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
>driver.wait(4000);
>Thread.sleep(20000);
Try this bellow code
WebDriver driver = new FirefoxDriver();
//Open Url
driver.get("https://www.alibaba.com/products/MAc_book.html");
Thread.sleep(3000);
//Gets all listed items in the page
List<WebElement> ele = driver.findElements(By.xpath(".//div[#class='l-page']//div[#class='l-page-main']//div[#class='m-product-item']//div[1]/a/img"));
//First link of that page
WebElement element3 = ele.get(0);
element3.click();
Set<String> windows=driver.getWindowHandles();
Iterator itr=(Iterator) windows.iterator();
//Moves to the newly opened window
while(itr.hasNext())
{
driver.switchTo().window((String)itr.next());
System.out.println("Window title is"+driver.getTitle());
}
//Click on Contact Supplier
element3 = driver.findElement(By.xpath(".//a[#title='Click to send an inquiry']"));
element3.click();
Try this code:
I tried it already and it is working:
driver.get("https://www.alibaba.com/products/MAc_book.html");
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[#data-hislog='60639615540']")));
WebElement element3 = driver.findElement(By.xpath("//a[#data-hislog='60639615540']"));
element3.click();
ArrayList<String> tabs2 = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs2.get(1));
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[normalize-space(text())='Contact Supplier']")));
WebElement contactSupplier = driver.findElement(By.xpath("//a[normalize-space(text())='Contact Supplier']"));
System.out.println(contactSupplier.getText());`
I am trying to navigate through search results from google with selenium webdriver. I have a interface for user to inset word to search and site title to choose. If the result is not on the first page the driver should go to next page to look for the site, and if not there than to next page and so on..
Somehow I don't manage to get beyond the second page end if I did get to the second page and the right site is there, the driver doesn't click on it.
Here is some of the code in Java:
private void setLoopNum(int l){
String getText = urlText.getText();
String getSiteName = linkToChoose.getText();
System.setProperty("webdriver.chrome.driver", "C:\\selenium-2.44.0\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize(); //Maximize window
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
for(int i=0;i<l;i++){
//WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
//driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
WebElement element1 = driver.findElement(By.name("q"));
element1.sendKeys(getText);
element1.submit();
//driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); //wait for page to load
//try{
boolean flag = false;
String page_number = "1";
while(! flag){
//get all the search results
List<WebElement> linkElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for(WebElement eachResult: linkElements){
if(eachResult.getAttribute(getSiteName).equals(getSiteName)){
eachResult.findElement(By.xpath("//a[#href='" + getSiteName + "']")).click();;
flag =true;
}else{
driver.findElement(By.xpath("//a[#id='pnnext']/span")).click();
linkElements.clear(); //celean list
break;
} //end else
}
}//end while loop
//}catch(Exception e){
// System.out.println("Error!");
// }
}
driver.quit(); //clear memory
}
Three things that you are missing in your code:
Firstly, in your code you are looking for only first element in your list.
Secondly, in getAttribute you are passing link instead of href:
if(eachResult.getAttribute(getSiteName).equals(getSiteName)){
it should be:
if(eachResult.getAttribute("href").equals(getSiteName)){
Thirdly, on clicking next the page is loaded via Google Ajax Api. Thus webdriver click will never block the execution of your code and will load linkElements with previous page links only. To avoid this let the driver get refreshed or put some wait for certain condition in your code.
Can u try out with this code:
WebDriverWait wait = new WebDriverWait(driver, 10)
while (!flag) {
// get all the search results
linkElements = wait
.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By
.xpath("//h3[#class='r']/a")));
for (WebElement eachResult : linkElements) {
if (eachResult.getAttribute("href").contains(getSiteName)) {
eachResult.click();
flag = true;
break;
}
}
if (!flag) {
driver.findElement(By.xpath("//a[#id='pnnext']/span[1]"))
.click();
pageNumber++;
linkElements.clear(); // celean list
wait.until(ExpectedConditions
.textToBePresentInElementLocated(
By.xpath("//td[#class='cur']"), pageNumber
+ "")); // Checking whether page number is changed as expected.
}
}// end while loop
EDIT:
List<WebElement> linkElements = new ArrayList<WebElement>();
ListIterator<WebElement> itr = null;
System.setProperty("webdriver.chrome.driver",
"webdrivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize(); // Maximize window
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://google.com");
WebElement element1 = driver.findElement(By.name("q"));
WebElement toClick = null;
element1.sendKeys(getText);
element1.submit();
// try{
int pageNumber = 1;
WebDriverWait wait = new WebDriverWait(driver, 10);
boolean flag = false;
while (!flag) {
linkElements = wait.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By
.xpath("//h3[#class='r']/a")));
itr = linkElements.listIterator(); // re-initializing iterator
while (itr.hasNext()) {
toClick = itr.next();
if (toClick.getAttribute("href").contains(getSiteName)) {
toClick.click();
flag = true;
break;
}
}
if (!flag) {
driver.findElement(By.xpath("//a[#id='pnnext']/span[1]"))
.click();
pageNumber++;
linkElements.clear(); // clean list
wait.until(ExpectedConditions.textToBePresentInElementLocated(
By.xpath("//td[#class='cur']"), pageNumber + ""));
}
}
driver.quit(); // clear memory
}
It looks like you're moving to the next page every time ANY of the WebElements in linkElements isn't what you're looking for. This will cause problems, as you need to relocate any elements that are re-rendered.
Give this a shot:
boolean found = false;
int page_number = 1; //If you need this as a string, you can make it one later
while(! found){
//get all the search results
List<WebElement> linkElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for(WebElement result: linkElements){
if(result.getAttribute("href").equals(getSiteName))
{
result.click();
found=true;
break;
}
}//End of foreach-loop
if(!found){
driver.findElement(By.xpath("//a[#id='pnnext']/span")).click();
page_number++;
}
}//End of while-loop
Also, you'll want to have some element-finding protection. Say that you search for something that has 0 results, or only one page of them (rare though that is). In the first case, you're lucky, because driver.findElements() should just return an empty list rather than throwing some exception, and the foreach loop just won't run, but in both cases, there won't be the anchor #pnnext, which will cause driver.findElement to throw an exception when you search for it. There are several ways to protect against this, such as writing a small wrapper function (IIRC, they have a simple implementation for findelementwithtimeoutwait() written on the Selenium website somewhere). I suggest you pick/write one and start using it, instead of the raw Selenium functions.
I am trying to select the drop down of this site and proceed to buy a show, but I am not able to do so please help.
System.setProperty("webdriver.chrome.driver", "C:/Selenium/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.theatrepeople.com/");
driver.findElement(By.id("edit-show")).click();
new Select(driver.findElement(By.id("edit-show"))).selectByVisibleText("The 39 Steps");
driver.findElement(By.id("edit-date-datepicker-popup-0")).click();
driver.findElement(By.linkText("27")).click();
driver.findElement(By.id("edit-ticket-no")).click();
new Select(driver.findElement(By.id("edit-ticket-no"))).selectByVisibleText("1 ticket");
driver.findElement(By.id("edit-submit-1")).click();
There is no reason to click on the select form (driver.findElement(By.id("edit-show")).click()), you just want to select an element (using the Select class). This is also probably the reason why your code is not working. You should remove this line and it should work.
Use the following code. It uses java script to select a text based upon it's valued. Really nice question. I also got to learn.
static WebDriver driver;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "D:\\ToCustomer_31_5_13\\src\\main\\resources\\Drivers\\chromedriver.exe");
driver = new FirefoxDriver();
driver.get("http://www.theatrepeople.com/");
driver.findElement(By.id("edit-show")).click();
WebElement show = driver.findElement(By.xpath("//div[#id = 'edit-show-wrapper']//div[#id = 'showNameWrap']"));
List<WebElement> l = show.findElements(By.tagName("option"));
String valueToSelect = getAttibuteValueForShow(l, "The American Plan");
driver.findElement(By.id("mini-basket-ajax")).click();
selectValueInDropDown(valueToSelect);
}
public static String getAttibuteValueForShow(List<WebElement> li, String showName)
{
int j =0;
String value = null;
for(int i =0; i<li.size(); i++)
{
j = j +1;
String dropDownText = li.get(i).getText();
if(dropDownText.equalsIgnoreCase(showName))
{
value = driver.findElement(By.xpath("//div[#id = 'edit-show-wrapper']//div[#id = 'showNameWrap']//option[" + j +"]")).getAttribute("value");
System.out.println(value);
break;
}
}
return value;
}
public static void selectValueInDropDown(String value)
{
JavascriptExecutor js = (JavascriptExecutor) driver;
String jsCmd = "document.getElementsByName('show')[0].value='" + value + "'";
js.executeScript(jsCmd);
}
The following code will work
WebDriver driver = new ChromeDriver();
driver.get("http://www.theatrepeople.com/");
WebElement dropDown = driver.findElement(By.id("edit-ticket-no"));
Select sel = new Select(dropDown);
sel.selectByVisibleText("1 ticket");