I want to be able to scroll the subscriptions list of my personal YouTube page, how do I do this? I have written code that allows me to scroll the main page, any ideas as to how the code could be tweaked to scroll the "My subscriptions" section of the YouTube page that appears when signed into YouTube?
package Check;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class java {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://www.youtube.com");
Thread.sleep(2500);
driver.findElement(By.xpath("//button[contains(.,'Sign in')]")).click();
Thread.sleep(1500);
driver.findElementById("Email").sendKeys("<My username>");
driver.findElementById("Passwd").sendKeys("<My password>");
driver.findElementById("signIn").click();
//driver.findElement(By.xpath("//button[contains(.,'Sign in')]")).click();
Thread.sleep(3500);
driver.findElementByCssSelector("div[id='identity-prompt-account-list'] > ul > label + label").click();
driver.findElementById("identity-prompt-confirm-button").click();
Thread.sleep(2500);
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollTo(0,Math.max(document.documentElement.scrollHeight," +
"document.body.scrollHeight,document.documentElement.clientHeight));");
Thread.sleep(5000);
driver.quit();
}
}
I have found by a method of trial and error a method that works, by the CSS selector appears to be limited to finding up to the 35th sibling so in the light of this limitation here is the code that I came up with this works very well for what I want to accomplish. Here is my script below:
package Check;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;
public class java2 {
public static void main(String[] args) throws InterruptedException {
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://www.youtube.com");
Thread.sleep(2500);
driver.findElement(By.xpath("//button[contains(.,'Sign in')]")).click();
Thread.sleep(1500);
driver.findElementById("Email").sendKeys("<User name>");
driver.findElementById("Passwd").sendKeys("<Password>");
driver.findElementById("signIn").click();
Thread.sleep(4000);
driver.findElementByCssSelector("div[id='identity-prompt-account-list'] > ul > label + label").click();
driver.findElementById("identity-prompt-confirm-button").click();
Thread.sleep(3000);
JavascriptExecutor js = (JavascriptExecutor)driver;
int i =0;
String CSSText = "ul[id='guide-channels'] > li";
do {
if (driver.findElementByCssSelector(CSSText).getText().equals("Josie Outlaw")){
break;
}
CSSText = CSSText + " + li";
i++;
} while (i<35);
js.executeScript("document.getElementsByClassName(\"vve-check overflowable-list-item guide-channel\")["+i+"].scrollIntoView(false);");
Thread.sleep(1500);
js.executeScript("document.getElementsByClassName(\"vve-check overflowable-list-item guide-channel\")["+i+"].scrollIntoView(true);");
Thread.sleep(10000);
driver.quit();
}
}
Related
I am attempting to fill the field on this website that asks for credit card, however selenium it not allowing me to send keys into the field. I believe this is because you must initially click on the field, but for some reason I can not get it to do that either. Does anyone have any insight?
Website: https://givingday.northeastern.edu/pages/giving-page-2
>
Under "Club Sports" click "Give", then click "Archery", then click "Next"
to get to CC field
package com.demo.testcases;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.Select;
public class StackOverFlow{
static WebDriver driver;
static WebDriverWait wait;
public static void main(String[] args) throws InterruptedException {
driver = new ChromeDriver();
driver.manage().window().maximize();
wait = new WebDriverWait(driver, 40);
driver.get("https://givingday.northeastern.edu/pages/giving-page-2");
Thread.sleep(1000);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".campaign-tiles-content")));
scrollDown(driver, "scroll(0,500)");
Thread.sleep(1000);
driver.findElement(By.xpath("//a[text()='Club Sports']/parent::div/following-sibling::div[#class='inline-b']"
+ "/descendant::button")).click();
Thread.sleep(1000);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".giving-form-billing")));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//h3[text()='Archery']")));
Thread.sleep(1000);
driver.findElement(By.xpath("//button[text()='load more causes']")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//h3[text()='Archery']")).click();
Thread.sleep(1000);
driver.findElement(By.xpath("//div[#class='flex-it']/descendant::input")).clear();
driver.findElement(By.xpath("//div[#class='flex-it']/descendant::input")).sendKeys("1");
Thread.sleep(1000);
driver.findElement(By.xpath("//button[text()='Next']")).click();
}
public static void scrollDown(WebDriver driver, String YoffSet){
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript(YoffSet);
}
}
There is a frame on this credit card input. You should first switch to frame then you can send a key.
driver.switchTo().frame(driver.findElement(By.id("spreedly-number-frame-1398")));
driver.findElement(By.id("card_number")).sendKeys(keysTosend);
public void enterCardDetails(String cardNumber) throws Throwable {
System.out.println(cardNumber.length());// it will print your card length
for (int i = 0; i < cardNumber.length(); i++) {
char c = cardNumber.charAt(i);
String s = new StringBuilder().append(c).toString();
driver.findElement(By.xpath("//*[#id='ccard_number']")).sendKeys(s);
}
}
Note:
You have to define and call cardnumber as per your requirement.
I am starting to learn how to handle multiple tabs in a browser using Selenium with Java. looks like my code below is not working.
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class HandlingWindows {
public static void main(String[] args) throws InterruptedException
{
WebDriver driver= new FirefoxDriver();
driver.get("https://www.facebook.com/");
String parent= driver.getWindowHandle();
System.out.println("Parent Window is"+parent);
//Get Data Policy
WebElement we= driver.findElement(By.linkText("Data Policy"));
//Click Data Policy link
we.click();
//Create an arrayList
ArrayList<String> s1= new ArrayList<String>(driver.getWindowHandles());
for(String s2:s1)
{
if(!(s2.equalsIgnoreCase(parent)))
{
driver.switchTo().window(s2);
Thread.sleep(5000);
System.out.println(driver.getWindowHandle());
System.out.println("get title of window"+driver.getTitle());
}
}
}
}
Please let me know how can I display the title 'Data Policy' without using
getWindowHandles().
getWindowHandles() works pretty fine but before invoking getWindowHandles() you have to induce WebDriverwait as follows :
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver= new FirefoxDriver();
driver.get("https://www.facebook.com/");
String parent= driver.getWindowHandle();
System.out.println("Parent Window is"+parent);
driver.findElement(By.linkText("Data Policy")).click();
WebDriverWait wait = new WebDriverWait(driver,5);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> s1= driver.getWindowHandles();
for(String s2:s1)
{
if(!parent.equalsIgnoreCase(s2))
{
driver.switchTo().window(s2);
Thread.sleep(5000);
System.out.println(driver.getWindowHandle());
System.out.println("get title of window"+driver.getTitle());
}
}
Console Output :
Parent Window is4294967297
4294967303
get title of windowData Policy
Just put Thread.sleep(3000); after clicking on Data Policy link.
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class HandlingWindows {
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
//D:\new folde backup\Selenium_project\seleniumproject\testNG_practice\driver
System.setProperty("webdriver.gecko.driver", "./driver/geckodriver.exe");
driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
String parent = driver.getWindowHandle();
System.out.println("Parent Window is" + parent);
// Get Data Policy
WebElement we = driver.findElement(By.linkText("Data Policy"));
// Click Data Policy link
we.click();
// Create an arrayList
Thread.sleep(3000);
ArrayList<String> s1 = new ArrayList<String>(driver.getWindowHandles());
System.out.println(s1);
for (String s2 : s1) {
if (!(s2.equalsIgnoreCase(parent))) {
driver.switchTo().window(s2);
Thread.sleep(5000);
System.out.println(driver.getWindowHandle());
System.out.println("get title of window" + driver.getTitle());
}
}
}
}
Output:-
Parent Window is4294967297
[4294967297, 4294967301]
4294967301
get title of windowData Policy
I have gecko driver installed already.
I am little bit confused in page scroll down.Console is not showing me any error as I have written Test Case failed if (if condition fails):
package PackageQandle;
//import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
//import junit.framework.Assert;
public class Adduser {
public static void main(String[] args) throws Throwable {
System.setProperty("webdriver.gecko.driver","C:/Users/sudhir/geckodriver-v0.18.0-win32/geckodriver.exe");
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://prod4.qandle.com");
WebDriverWait webwait = new WebDriverWait(driver,120);
webwait.until(ExpectedConditions.elementToBeClickable(driver.findElementByXPath(".//*[#id='login-email']")));
WebElement web = driver.findElementByXPath(".//*[#id='login-email']");
web.sendKeys("Anil#gmail.com");
WebDriverWait webwait1 = new WebDriverWait(driver,20);
webwait1.until(ExpectedConditions.elementToBeClickable(driver.findElementByXPath(".//*[#id='login-password']")));
WebElement web1 = driver.findElementByXPath(".//*[#id='login-password']");
web1.sendKeys("Abc12345");
WebElement web2 = driver.findElementByXPath(".//*[#id='signInSubmit']");
web2.submit();
//Assert.assertEquals(my_Title, my_ExpectedTitle);
Thread.sleep(5000);
//JavascriptExecutor j = new JavascriptExecutor();
String my_Title = driver.getCurrentUrl();
//System.out.println(my_Title);
String my_ExpectedTitle = "https://prod4.qandle.com/#/";
if(my_Title.equals(my_ExpectedTitle)){
driver.executeScript("Scroll(0,600);");
}else{
System.out.println("Test Case Failed");
}
}
}
I am using this code to inspect element which appears when I scroll down the page.
The Syntax of findElementByXpath must be
driver.findElement(By.xpath(".//*[#id='login-password']"));
Try the below mentioned code for scrolling to element, it worked for me
driver.get("https://prod4.qandle.com");
WebDriverWait webwait = new WebDriverWait(driver,120);
webwait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath(".//*[#id='login-email']"))));
WebElement web = driver.findElement(By.xpath(".//*[#id='login-email']"));
web.sendKeys("Anil#gmail.com");
WebDriverWait webwait1 = new WebDriverWait(driver,20);
webwait1.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath(".//*[#id='login-password']"))));
WebElement web1 = driver.findElement(By.xpath(".//*[#id='login-password']"));
web1.sendKeys("Abc12345");
WebElement web2 = driver.findElement(By.xpath(".//*[#id='signInSubmit']"));
web2.submit();
//Assert.assertEquals(my_Title, my_ExpectedTitle);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String my_Title = driver.getCurrentUrl();
String my_ExpectedTitle = "https://prod4.qandle.com/#/";
if(my_Title.equals(my_ExpectedTitle)){
JavascriptExecutor js = (JavascriptExecutor) driver;
// Mention the xpath of the element to be scrolled for
WebElement tempElement=driver.findElement(By.xpath("//*[contains(text(),'Reports')]"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", tempElement);
}else{
System.out.println("Test Case Failed");
}
If you are using "Chrome" use:
js.ExecuteScript("arguments[0].scrollIntoViewIfNeeded(true);", e)
For "Firefox" and "IE" use:
js.ExecuteScript("arguments[0].scrollIntoView(true);" +
"window.scrollBy(0,-100);", e);
You need to cast driver to JavascriptExecutor type
JavascriptExecutor jse = (JavascriptExecutor) deiver;
WebElement scrollElement = driver.findElement();
jse.executeScript("return arguments[0].scrollIntoView();", scrollElement);
Till yesterday the below mentioned code was working fine but now i am facing some problem .
The code opens firefox browser then loads facebook.com but the code is not sending
email and password to web browser i.e. sendkeys() is not working.
I verified the id of both textbox of email and password which are correct yet code is not working .
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
public class Webdriver2 {
WebDriver driver ;
JavascriptExecutor jse;
public void invokeBrowser()
{
try
{
System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.19.0-win64\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS );
driver.get("https://www.facebook.com/");
search();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void search()
{
try
{
driver.findElement(By.id("email")).sendKeys("example#gmail.com");
Thread.sleep(4000);
driver.findElement(By.id("pass")).sendKeys("password");
Thread.sleep(4000);
driver.findElement(By.id("u_0_2")).click();
Thread.sleep(4000);
/*driver.findElement(By.name("q")).sendKeys("spit mumbai");
Thread.sleep(4000);
driver.findElement(By.xpath(" //button[#aria-label='Search' and #data-testid='facebar_search_button'] ")).click();*/
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Webdriver2 w = new Webdriver2();
w.invokeBrowser();
}
}
Try clicking on the two textboxes before you are performing the sendKeys:
driver.findElement(By.id("email")).click();
driver.findElement(By.id("email")).sendKeys("example#gmail.com");
The textboxes probably needs focus.
We need to take care of a couple of things here as follows:
The Email or Phone field is within an <input> tag so we need to take it into account while selecting the locator.
The Password field is also within an <input> tag so we need to take it into account while selecting the locator.
If you observe closely the id of the Log In button is dynamic and also within an <input> tag, so we need to consider this factor as well.
Here is the minimum sample code block using cssSelector to access the url https://www.facebook.com/, provide Email or Phone and Password, finally click on Log In button:
package demo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Facebook_Login_CSS_FF {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.findElement(By.cssSelector("input#email")).sendKeys("Ryusei");
driver.findElement(By.cssSelector("input[name='pass']")).sendKeys("Nakamura");
driver.findElement(By.cssSelector("input[value='Log In']")).click();
}
}
I tried this exact code on other websites and it seems to work fine. It's just on pizza hut that it can't even locate an element let alone click on it. Thread.sleep() doesn't make a difference. The problem is between the commented *, according to the compiler. Here's the code.
package training;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class PizzaHut {
WebDriver driver;
#Test
public void open() throws Exception {
//SET UP WEBDRIVER AND OPEN WEBSITE
System.setProperty("webdriver.chrome.driver","/Users/1mr4n/Downloads/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.pizzahut.com/#/home");
Thread.sleep(1000);
//CLICK PIZZA
Thread.sleep(5000);
test("before");
//**************PROBLEM*CODE**********************
driver.findElement(By.xpath("//a[#id='lg-nav-pizza']")).click();
//************************************************
test("clicked pizza");
//CLOSE BROWSER
Thread.sleep(15000);
driver.close();
}
public static void test(String x) {
System.out.println(x);
}
}
I just ran the code below and it worked just fine. No need for sleep or waits and I'm using Chrome also.
driver.get("https://www.pizzahut.com");
driver.findElement(By.id("lg-nav-pizza")).click();
Try this one ,definitely it help you.
package training;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class PizzaHut {
WebDriver driver;
#Test
public void open() throws Exception {
//SET UP WEBDRIVER AND OPEN WEBSITE
// System.setProperty("webdriver.chrome.driver","/Users/1mr4n/Downloads/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.pizzahut.com/#/home");
Thread.sleep(1000);
//CLICK PIZZA
Thread.sleep(5000);
test("before");
List<WebElement> webElements=driver.findElement(By.cssSelector("div.btn-group.btn-group-lg.btn-group-justified.ph-header-navigation"))
.findElements(By.cssSelector("div.btn.btn-link.ph-ghost-padding.ng-scope"));
for (WebElement element : webElements) {
if (element.getAttribute("title").equals("PIZZA")) {
element.click();
}
}
Thread.sleep(5000);
test("clicked pizza");
//CLOSE BROWSER
Thread.sleep(15000);
driver.close();
}
public static void test(String x) {
System.out.println(x);
}
}
You are not able to click it because it is an AngularJS tag, hence it takes some time to load: add some wait like below and it works (Here i'm just adding thread.sleep for the sake of simplicity,I've increased it to 15000ms):
//CLICK PIZZA
Thread.sleep(15000);
test("before");
//**************PROBLEM*CODE**********************
driver.findElement(By.xpath("//a[#id='lg-nav-pizza']")).click();