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
Related
This is the html code for the button in the pop up ( pop up has a lead gen form) -
<button id="getCoupon" class="fetch" data-bind="click: submitForm" type="submit">Fetch Coupon</button>
This is the script which I have written in JAVA in Eclipse. I am able to fill the name, Email and Phone number but I'm not able to click on the button -
driver.findElement(By.id("getCoupon")).click();
As per the comment and URL, you have shared :
You can try with this code :
public class Pawan {
static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user**\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://vets.cm.qa.preview.vca.webstagesite.com/free-first-exam");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("input[value='/santa-monica']~div.select-btn"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("fName"))).sendKeys("Pawan");
wait.until(ExpectedConditions.elementToBeClickable(By.id("lName"))).sendKeys("Sharma");
wait.until(ExpectedConditions.elementToBeClickable(By.id("email"))).sendKeys("ps12#gmail.com");
wait.until(ExpectedConditions.elementToBeClickable(By.id("zip"))).sendKeys("90404");
wait.until(ExpectedConditions.elementToBeClickable(By.id("phone"))).sendKeys("9697989900");
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,100)", "");
wait.until(ExpectedConditions.elementToBeClickable(By.id("getCoupon"))).click();
}
}
As per your HTML code, your id is : "getCoupon",
whereas in code you mentioned id as : "getCouponFetch". Please correct and it should work. Code -
driver.findElement(By.id("getCoupon")).click();
If selenium click don't work, use below Java Script click code :
WebElement element = driver.findElement(By.id("getCoupon")); JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("arguments[0].click();", element);
Firstly, what kind of error did you get??
Try using implicit wait if your getting "NoSuchElementException" like below:
driver.manage().timeOuts().implicitlywait(30,TimeUnit.SECONDS);
Then try using the below way to locate that button:
driver.findElementByXpath("text()[contains(.,'Fetch Coupon')]").click();
As per the HTML you have shared to click() on the button you have to induce WebDriverWait for the desired element to be clickable and you can use either of the following solutions:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.fetch#getCoupon"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#class='fetch' and #id='getCoupon'][contains(.,'Fetch Coupon')]"))).click();
Update
As an alternative you can use the executeScript() method to invoke the click() as follows:
Using cssSelector:
WebElement fetch_coupon = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.fetch#getCoupon")));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", fetch_coupon);
Using xpath:
WebElement fetch_coupon = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#class='fetch' and #id='getCoupon'][contains(.,'Fetch Coupon')]")));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", fetch_coupon);
This question already has an answer here:
How to click on particular element in a list using selenium webdriver?
(1 answer)
Closed 4 years ago.
I got this as an interview question.
Need help to solve this
Scenario: There is this web page which has a list of 10 web link. Click on each web link and open in new window or tab using selenium Java .
Example here.
Click on all tutorial from WebDriver Tutorial. which should open in a new tab
As per your response in comment section, you can achieve the same behavior through Actions class which is available in selenium.
You can try out this code :
public class Amisha {
static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user***\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.guru99.com/selenium-tutorial.html");
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,650)", "");
List<WebElement> element = driver.findElements(By.xpath("//strong[text()='WebDriver Tutorial']/following-sibling::table[1]/descendant::a"));
Actions action = new Actions(driver);
for(WebElement ele:element) {
action.keyDown(Keys.LEFT_CONTROL).moveToElement(ele).click().keyUp(Keys.LEFT_CONTROL).build().perform();
}
}
}
you can achieve this using the JavascriptExecutor
First, Capture all the required link element in list
Iterate all the list element and get the href value from the anchor tag
Open the window using the JavaScript executor by passing the above href value
Code:
public static void main(String args[]) {
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.guru99.com/selenium-tutorial.html");
driver.manage().window().maximize();
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.titleContains("Selenium Tutorial"));
List<WebElement> tutorialLinkList=driver.findElements(By.xpath("//strong[contains(text(),'Tutorial')]/ancestor::a"));
JavascriptExecutor js=(JavascriptExecutor)driver;
//I have just clicked only 10 link. If you want to iterate all the available links, then use foreach loop
for(int i=0;i<10;i++){
String url=tutorialLinkList.get(i).getAttribute("href");
js.executeScript("window.open(arguments[0])",url); //New Tab will be opened
}
}
Note: Here, I have opened only the first 10 links in different tab. If you wish to open all the link in new tab,then I would suggest to use foreach loop as below
for(WebElement tutoialLink : tutorialLinkList){
String url=tutoialLink.getAttribute("href");
js.executeScript("window.open(arguments[0])",url); //New Tab will be opened
}
Edit: Code with Actions Class
It looks right click is not working in that URL and hence, you can open the link is new tab by performing Ctr + click action as below
public static void main(String args[]) {
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.guru99.com/selenium-tutorial.html");
driver.manage().window().maximize();
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.titleContains("Selenium Tutorial"));
List<WebElement> tutorialLinkList=driver.findElements(By.xpath("//strong[contains(text(),'Tutorial')]/ancestor::a"));
Actions action = new Actions(driver);
//I have just clicked only 10 link. If you want to iterate all the available links, then use foreach loop
for(int i=0;i<10;i++){
action.keyDown(Keys.CONTROL).click(tutorialLinkList.get(i)).keyUp(Keys.CONTROL).build().perform();
}
}
Not able to Select the month for Date of Birth.
Code I am using is:
driver.findElement(By.xpath(".//*[#id = 'BirthMonth']/div")).click();
Thread.sleep(3000);
WebElement months = driver.findElement(By.xpath(".//[#id='BirthMonth']/div[2]/div[#id=':1']"));
Thread.sleep(2000);
months.click();
I also tried with by using DropDownList case. But Not able to set any Month.
Please Say me the Solution.
You can use keyboard event replace mouse.
WebElement birthMonth = driver.findElement(By.id("BirthMonth"));
birthMonth.click();
Actions action = new Actions(driver);
action.sendKeys(Keys.DOWN).sendKeys(Keys.ENTER).perform();
We can use sendKeys directly:
driver.findElement(By.xpath(".//*[#id='BirthMonth']/div[1]")).sendKeys("July");
You can wrap this up in a function
public void selectBirthMonth(int monthIndex)
{
driver.findElement(By.cssSelector("#BirthMonth > div")).click();
driver.findElements(By.cssSelector("#BirthMonth > div.goog-menu > div.goog-menuitem")).get(monthIndex - 1).click();
}
and then call it like
selectBirthMonth(9); // 1 = January
WebElement month = wd.findElement(By.xpath("//[#id=\"BirthMonth\"]/div[1]"));
month.click();
Thread.sleep(3000);
//wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//fetch months from the dropdown and store it in a list
List<WebElement> month_dropdown = wd.findElements(By.xpath("//[#id=\"BirthMonth\"]/div[2]/div/div"));
//iterate the list and get the expected month
for (WebElement month_ele:month_dropdown){
String expected_month = month_ele.getAttribute("innerHTML");
// Break the loop if match found
if(expected_month.equalsIgnoreCase("August")){
month_ele.click();
break;
}
}
It is not drop down value , you have to click on drop down arrows and then click on any value which you have to pass from script.
Code is below:
System.setProperty("webdriver.chrome.driver", "E:/software and tools/chromedriver_win32/chromedriver.exe");
WebDriver driver= new ChromeDriver();
//FirefoxDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://accounts.google.com/SignUp");
Thread.sleep(5000);
driver.findElement(By.xpath(".//*[#id='BirthMonth']/div[1]/div[2]")).click();
driver.findElement(By.xpath(".//*[#id=':7']/div")).click();
it is workable code for Birthmonth
Please find below link for same type of Question
Not able to select the value from drop down list by using Select method in Selenium
I'm trying to click on state link given url then print title of next page and go back, then click another state link dynamically using for loop. But loop stops after initial value.
My code is as below:
public class Allstatetitleclick {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.adspapa.com/");
WebElement catBox = driver.findElement(By.xpath("html/body/table[1]/tbody/tr/td/table/tbody/tr/td[1]/table"));
List<WebElement> catValues = catBox.findElements(By.tagName("a"));
System.out.println(catValues.size());
for(int i=0;i<catValues.size();i++){
//System.out.println(catValues.get(i).getText());
catValues.get(i).click();
System.out.println(driver.getTitle());
driver.navigate().back();
}
System.out.println("TEST");
}
}
The problem is after navigating back the elements found previously will be expired. Hence we need to update the code to refind the elements after navigate back.
Update the code below :
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.adspapa.com/");
WebElement catBox = driver.findElement(By.xpath("html/body/table[1]/tbody/tr/td/table/tbody/tr/td[1]/table"));
List<WebElement> catValues = catBox.findElements(By.tagName("a"));
for(int i=0;i<catValues.size();i++)
{
catValues.get(i).click();
System.out.println(driver.getTitle());
driver.navigate().back();
catBox = driver.findElement(By.xpath("html/body/table[1]/tbody/tr/td/table/tbody/tr/td[1]/table"));
catValues = catBox.findElements(By.tagName("a"));
}
driver.quit();
I have tested above code at my end and its working fine.You can improve the above code as per your use.
Note: I have executed this and its working fine now.It will give you the size and clicking on every link.It was a issue where you need to go inside the Frame.
It has a Frame where you need to switch.
Please copy and paste and execute it.
Hope you find your answer.
I have the following HTML:
<button name="btnG" class="gbqfb" aria-label="Google Search" id="gbqfb"><span class="gbqfi"></span></button>
My following code for clicking "Google Search" button is working well using Java in WebDriver.
driver.findElement(By.id("gbqfb")).click();
I want to use JavaScript with WebDriver to click the button. How can I do it?
Executing a click via JavaScript has some behaviors of which you should be aware. If for example, the code bound to the onclick event of your element invokes window.alert(), you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use the JavascriptExecutor class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.
// Assume driver is a valid WebDriver instance that
// has been properly instantiated elsewhere.
WebElement element = driver.findElement(By.id("gbqfd"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
You should also note that you might be better off using the click() method of the WebElement interface, but disabling native events before instantiating your driver. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.
Here is the code using JavaScript to click the button in WebDriver:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('gbqfb').click();");
I know this isn't JavaScript, but you can also physically use the mouse-click to click a dynamic Javascript anchor:
public static void mouseClickByLocator( String cssLocator ) {
String locator = cssLocator;
WebElement el = driver.findElement( By.cssSelector( locator ) );
Actions builder = new Actions(driver);
builder.moveToElement( el ).click( el );
builder.perform();
}
Not sure OP answer was really answered.
var driver = new webdriver.Builder().usingServer('serverAddress').withCapabilities({'browserName': 'firefox'}).build();
driver.get('http://www.google.com');
driver.findElement(webdriver.By.id('gbqfb')).click();
You can't use WebDriver to do it in JavaScript, as WebDriver is a Java tool. However, you can execute JavaScript from Java using WebDriver, and you could call some JavaScript code that clicks a particular button.
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.document.getElementById('gbqfb').click()");
By XPath: inspect the element on target page, copy Xpath and use the below script:worked for me.
WebElement nameInputField = driver.findElement(By.xpath("html/body/div[6]/div[1]/div[3]/div/div/div[1]/div[3]/ul/li[4]/a"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", nameInputField);
const {Builder, By, Key, util} = require('selenium-webdriver')
// FUNÇÃO PARA PAUSA
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function example() {
// chrome
let driver = await new Builder().forBrowser("firefox").build()
await driver.get('https://www.google.com.br')
// await driver.findElement(By.name('q')).sendKeys('Selenium' ,Key.RETURN)
await sleep(2000)
await driver.findElement(By.name('q')).sendKeys('Selenium')
await sleep(2000)
// CLICAR
driver.findElement(By.name('btnK')).click()
}
example()
Com essas últimas linhas, você pode clicar !
This code will perform the click operation on the WebElement "we" after 100 ms:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("var elem=arguments[0]; setTimeout(function() {elem.click();}, 100)", we);
Another easiest solution is to use Key.RETUEN
Click here for solution in detail
driver.findElement(By.name("q")).sendKeys("Selenium Tutorial", Key.RETURN);
I think some parts of above codes has changed a little, I'm learning Selenium with JavaScript and I founded 2 options to click
To start we need to find the element we want to click, could be By (id, class, etc.), here is how, https://www.youtube.com/watch?v=BQ-9e13kJ58&list=PLZMWkkQEwOPl0udc9Dap2NbEAkwkdOTV3.
Right down are the 2 ways that I'm talking about:
FIRST Method:
await driver.findElement(By.id("sampletodotext")).sendKeys("Learning Selenium", Key.RETURN);
- Here we found an empty field by it's Id, and then we write "Learning Selenium" in this field with the sendKeys().
- Key.RETURN: Simulate the person pressing the ENTER key in keyboard.
SECOND Method:
await driver.findElement(By.id("sampletodotext")).sendKeys("Learn Selenium");
await driver.findElement(By.id("addbutton")).click().finally();
- The difference here, is we switched the Key.RETURN of the FIRST method, for the entire second line, in the SECOND method.
Use the code below, which worked for me:
public void sendKeysJavascript() {
String file = getfile();
WebElement browser = driver.findElement(By.xpath("//input[#type='file']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
actionClass.waitforSeconds(5);
js.executeScript("arguments[0].click();", browser);
actionClass.waitforSeconds(1);
browser.sendKeys(file);
}
String getfile() {
return new File("./src/main/resources/TestData/example.pdf").getAbsolutePath();
}
Don't forget to add wait time before the js click action. It is mandatory
Cross browser testing java scripts
public class MultipleBrowser {
public WebDriver driver= null;
String browser="mozilla";
String url="https://www.omnicard.com";
#BeforeMethod
public void LaunchBrowser() {
if(browser.equalsIgnoreCase("mozilla"))
driver= new FirefoxDriver();
else if(browser.equalsIgnoreCase("safari"))
driver= new SafariDriver();
else if(browser.equalsIgnoreCase("chrome"))
//System.setProperty("webdriver.chrome.driver","/Users/mhossain/Desktop/chromedriver");
driver= new ChromeDriver();
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
driver.navigate().to(url);
}
}
but when you want to run firefox you need to chrome path disable, otherwise browser will launch but application may not.(try both way) .