I am not able to scroll Google's results page to the end. Could anyone give me pointers on the below code 1. Tried to do using JS by the following
(a)j.executeScript("window.scrollTo(0,500)")
(b)j.executeScript("window.scrollBy(250,350)")
(c)j.executeScript("window.scrollTo(0,document.documentElement.scrollHeight")**
WebDriver driver = new ChromeDriver();
driver.navigate().to("https://www.google.com");
driver.manage().window().maximize();
// Google News
driver.findElement(By.id("lst-ib")).click();
driver.findElement(By.id("lst-ib")).sendKeys("News");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.RETURN);
Thread.sleep(2000);
driver.findElement(By.xpath("//div[#class='rc']//a")).click();
Thread.sleep(4000);
JavascriptExecutor j = (JavascriptExecutor)driver;
for(int i=1;i<=3;i++)
{
j.executeScript("window.scrollTo(0,500)");
}
}
}
Use this:
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,250)");
Scroll to particular element
js.executeScript("arguments[0].scrollIntoView(true);",element);
Here element is your Webelement from where you wanted to scroll
or you can use Robot class
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PAGE_DOWN);
robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
Change below code
for(var i=1;i<=3;i++)
{
j.executeScript("window.scrollTo(0,500)");
}
to
for(int i=1;i<=3;i++)
{
j.executeScript("window.scrollTo(0, arguments[0]*500)", i);
}
And it should work. 500 that you used is absolute value and not a delta for scroll. Or else use scrollBy
for(int i=1;i<=3;i++)
{
j.executeScript("window.scrollBy(0,500)");
}
j.executeScript("window.scrollBy(0,250)", "");
OR, you can do as follows:
j.executeScript("scroll(0, 250);");
Related
I am new to selenium. I am trying to automate Naukri homepage.
However, in the field location, sendKeys(Keys.ARROW_DOWN) is not working. Code is working fine till a.sendKeys("ch").
I am using below code. Please guide.
driver.findElement(By.xpath("//input[#class='sugInp']")).sendKeys("java");
Thread.sleep(2000);
List<WebElement> options = driver.findElements(By.xpath("//ul[#class='Sdrop']/li/div/strong"));
for(WebElement o:options)
{
if(o.getText().equalsIgnoreCase("developer"))
{
o.click();
System.out.println("success");
break;
}
}
Thread.sleep(5000);
Robot r = new Robot();
r.keyPress(KeyEvent.VK_TAB);
System.out.println("Tab success");
Actions a = new Actions(driver);
a.sendKeys("ch");
a.sendKeys(Keys.ARROW_DOWN);
a.sendKeys(Keys.ARROW_DOWN);
a.sendKeys(Keys.ENTER);
a.build().perform();
I think you miss your element. Please try this one.
WebElement txtUsername = driver.findElement(By.id("email"));
Actions builder = new Actions(driver);
Action seriesOfActions = builder
.moveToElement(txtUsername)
.click()
.keyDown(txtUsername, Keys.SHIFT)
.sendKeys(txtUsername, "hello")
.keyUp(txtUsername, Keys.SHIFT)
.doubleClick(txtUsername)
.contextClick()
.build();
seriesOfActions.perform() ;
Why don't you just click on the desired element from the list, instead of using Actions
This is how it will look without Actions
driver.findElement(By.xpath("//input[#class='sugInp']")).sendKeys("java");
Thread.sleep(2000);List<WebElement> options = driver.findElements(By.xpath("//ul[#class='Sdrop']/li/div/strong"));
for (WebElement o : options) {
if (o.getText().equalsIgnoreCase("developer")) {
o.click();
System.out.println("success");
break;
}
}
Thread.sleep(3000);
driver.findElement(By.cssSelector("input#qsb-location-sugg.sugInp")).sendKeys("ch");
Thread.sleep(3000);
List<WebElement> elements = driver.findElements(By.xpath("//*[#id='sugDrp_qsb-location-sugg']/ul/li"));
System.out.println(elements.get(1).getText());
elements.get(1).click();
And don't use Thread.sleep() anywhere in your script, make sure to use waits.
I need to refresh WebElement in Selenium Webdriver without reload page.
When i use a while, the text of the page element is constantly updated because it is a chat, but the loop carries only the same text.
while (driver.FindElements(By.ClassName("chat")).Count() > 0)
{
{
var element = driver.FindElement(By.ClassName("_chat")).Text;
Console.WriteLine(element);
}
}
I am using a C# project.
Thanks!
Sorry i use java
If you get element outdated errors
you can use it
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("_chat")));
Instead of
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.name("_chat"))));
not use driver.findElement
Try this.
for (int i = 0; i < 5; i++) {
while (driver.FindElements(By.ClassName("chat")).Count() > 0)
{
{
var element = driver.FindElement(By.ClassName("_chat")).Text;
Console.WriteLine(element);
}
}
}
Why am I getting errors when trying to get the driver to click on the reCAPTCHA button?
This is the site where I am trying to get it to work: https://rsps100.com/vote/760/
This is my current code so far:
WebElement iframeSwitch = driver.findElement(By.xpath("/html/body/div[1]/div/div[1]/div/div/div[2]/div/form/div/div/div/div/iframe"));
driver.switchTo().frame(iframeSwitch);
driver.findElement(By.cssSelector("div[class=recaptcha-checkbox-checkmark]")).click();
To invoke click() on the reCaptcha checkbox as the element is within an <iframe> you need to:
Induce WebDriverWait for the desired frameToBeAvailableAndSwitchToIt.
Induce WebDriverWait for the desired elementToBeClickable.
You can use the following solution:
Code Block:
public class ReCaptcha_click {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
WebDriver driver = new ChromeDriver(options);
driver.get("https://rsps100.com/vote/760");
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[starts-with(#name, 'a-') and starts-with(#src, 'https://www.google.com/recaptcha')]")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.recaptcha-checkbox-checkmark"))).click();
}
}
Browser Snapshot:
Use WebDriverWait to identify the element.See if this help.
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[starts-with(#name,'a-')]")));
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.recaptcha-checkbox-checkmark")));
element.click();
This worked for me. Please note that I am using Selenide. For regular selenium code look the same.
import static com.codeborne.selenide.Selenide.*;
void recaptchaTest() {
open("https://rsps100.com/vote/760");
switchTo().frame($x("//iframe[starts-with(#name, 'a-') and starts-with(#src, 'https://www.google.com/recaptcha')]"));
$("div.rc-anchor-content").click();
switchTo().defaultContent();
}
Here is the code that should work.
driver.switchTo().frame("a-9wt0e8vkopnm");
driver.findElement(By.xpath("//span[#id='recaptcha-anchor']")).click();
I solved this maybe on the stupid way. But hawe in mind that I am not in test environment and I practicing automatization of tests. So this is my solution:
Beside using
public void notABot( ) {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds( 15 ));
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[starts-with(#name,'a-') and starts-with (#src, 'https://www.google.com/recaptcha')]")));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div [ #class = 'recaptcha-checkbox-border']"))).click( );
driver.switchTo().defaultContent();
}
this, I also added custom send keys method
public void inputEmail( ) {
inputEmail.click( );
String email = Strings.EMAIL_FOR_SIGNUP;
for (int i = 0; i < email.length(); i++) {
char c = email.charAt(i);
String s = new StringBuilder( ).append( c ).toString( );
inputEmail.sendKeys( s );
sleepSendKeys( );
}
}
Sleep is 300 millis. In 96 procent time I manage to cheat google reCaptcha that actually human is login to the page. Its work for me
I want to select alternate values from the list below.my current code is as follows:
WebDriver driver;
System.setProperty
("webdriver.chrome.driver", "D:\\softwares\\gecko\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://demoqa.com/selectable/");
System.out.println("url opened");
List<WebElement> list=driver.findElements(By.xpath("//ol[contains(#class,'ui-selectable')]"));
Thread.sleep(3000);
Actions builder= new Actions(driver);
Action build= builder.click(list.get(0)).sendKeys(Keys.CONTROL).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build();
build.perform();
}
}
First we need to get all the elements, then go to the alternative elements and click on it.
List<WebElement> list = driver.findElements(By.xpath("//*[#id='selectable']/li"));
Use the above xpath to get all the elements, once you got all the elements traverse to alternative elements.
Actions builder = new Actions(driver);
for (int i = 0; i < list.size(); i += 2) {
builder.click(list.get(i)).sendKeys(Keys.CONTROL).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).perform();
System.out.println("item clicked" + list.get(i).getText());
}
I am facing problem to identify the object when i move forward and comeback to parent page.
Here is the scenario. I would like to click on each link in a home page and print page title and navigate back to home page.
Following is the code which i tried. It works fine clicking on the first link and coming back to HomePage. At this point of time, the List Object needs to be identified excluding already visited links. How to do that?
In QTP, we have RefreshObject and Init to do this. Is there a similar method in WebDriver?
WebDriver driver = new FirefoxDriver();
driver.get("http://www.googl.com/");
driver.manage().window().maximize();
List<WebElement> objWEs = driver.findElements(By.tagName("a"));
for(WebElement e:objWEs)
{
if(!e.getText().isEmpty())
{
e.click();
System.out.println(driver.getTitle());
driver.navigate().back();
}
}
driver.close();
As soon as you navigate to another web-page, or even switch into an iframe in the same web-page, any WebElement object that you have in memory is potentially "stale".
One optional solution, is to list down all the element IDs, and then iterate that list instead:
Set<String> linkIds = new HashSet<String>();
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links)
{
if(!link.getText().isEmpty())
linkIds.add(link.getAttribute("id"));
}
for (String linkId : linkIds)
{
driver.findElement(By.id(linkId)).click();
System.out.println(driver.getTitle());
driver.navigate().back();
}
Please note, however, that all the above is under the assumption that each link has a unique ID, and that all the links remain in the web-page when you navigate back into it. If this is not the case in the specific web-page that you are accessing, then an alternative approach is required here.
Instead of iterating the link-IDs, you can iterate the link-indexes, assuming that the links remain in the same order when you navigate in and out of the web-page. This is somewhat less efficient though, because you have to retrieve the entire list of all the links at the beginning of each iteration.
for (int i=0; true; i++)
{
List<WebElement> links = driver.findElements(By.tagName("a"));
if (i >= links.size())
break;
links.get(i).click();
System.out.println(driver.getTitle());
driver.navigate().back();
}
The code above should work even if the links do not remain in the same order when you navigate back into the web-page. However, under such scenario, you will most likely miss out on some of them.
Here is the complete code for my above problem.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
driver.get("http://www.googl.com/");
driver.manage().window().maximize();
for (int i=0; true; i++)
{
List<WebElement> links = driver.findElements(By.tagName("a"));
if (i >= links.size())
break;
WebElement ele=links.get(i);
if(!ele.getText().isEmpty())
{
ele.click();
System.out.println(driver.getTitle());
driver.navigate().back();
}
}
driver.close();