Java Selenium + 2Captcha + Submit Form - java

Hello i am trying to automate some process here . i am using 2captch to solve captcha , please check out image .
I have got site_key and api_key , now i am sending api_key + site_key and it is returning me response_token, i have added returned response token into g-recaptcha-response but it is not submitting form.
what i want is that : i can solve captcha and submit form .
Here is my current java code :
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
ChromeDriver driver;
driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.get("https://id.sonyentertainmentnetwork.com/signin/?client_id=fe1fdbfa-f1a1-47ac-b793-e648fba25e86&redirect_uri=https://secure.eu.playstation.com/psnauth/PSNOAUTHResponse/pdc/&service_entity=urn:service-entity:psn&response_type=code&scope=psn:s2s&ui=pr&service_logo=ps&request_locale=en_GB&error=login_required&error_code=4165&error_description=User+is+not+authenticated&no_captcha=false#/signin?entry=%2Fsignin");
Thread.sleep(5000);
driver.findElement(By.xpath("//input[#title='Sign-In ID (Email Address)']")).sendKeys("email");
Thread.sleep(2000);
driver.findElement(By.xpath("//input[#title='Password']")).sendKeys("password");
Thread.sleep(2000);
driver.findElement(By.xpath("//button[#class='primary-button row-button text-button touch-feedback']")).click();
Thread.sleep(3000);
By captcha = By.xpath("//iframe[#title='recaptcha challenge']");
String src = driver.findElement(captcha).getAttribute("src");
String key = getKey(src);
System.out.println(key);
String apiKey = "API_KEY";
String googleKey = key;
String pageUrl = "https://id.sonyentertainmentnetwork.com/signin/?client_id=fe1fdbfa-f1a1-47ac-b793-e648fba25e86&redirect_uri=https://secure.eu.playstation.com/psnauth/PSNOAUTHResponse/pdc/&service_entity=urn:service-entity:psn&response_type=code&scope=psn:s2s&ui=pr&service_logo=ps&request_locale=en_GB&error=login_required&error_code=4165&error_description=User+is+not+authenticated&no_captcha=false#/signin?entry=%2Fsignin";
String proxyIp = "183.38.231.131";
String proxyPort = "8888";
String proxyUser = "username";
String proxyPw = "password";
TwoCaptchaService service = new TwoCaptchaService(apiKey, googleKey, pageUrl, proxyIp, proxyPort, proxyUser, proxyPw, ProxyType.HTTP);
try {
String responseToken = service.solveCaptcha();
System.out.println("The response token is: " + responseToken);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById(\"g-recaptcha-response\").innerHTML = \'"+responseToken+"\';");
} catch (InterruptedException e) {
System.out.println("ERROR case 1");
e.printStackTrace();
} catch (IOException e) {
System.out.println("ERROR case 2");
e.printStackTrace();
}
UPDATED CODE :
js.executeScript("document.getElementById(\"g-recaptcha-response\").innerHTML = \'" + responseToken + "\';");
Thread.sleep(500);
WebElement frameElement = driver.findElement(captcha);
driver.switchTo().frame(frameElement);
js.executeScript("document.getElementById('recaptcha-verify-button').click();");
it is clicking on button but , it shows Please select all matching images.
. please check out screenshot

All you need to do is submit it like this:
js.executeScript("document.getElementById('g-recaptcha-response').innerHTML='" + responseToken + "';");
Thread.sleep(500);
js.executeScript("document.getElementById('captcha-form').submit();");
also don't forget to check this ID : "captcha-form", it can be different
To reach to element "recaptcha-verify-button":
After you got the response from the API;
By frame = By.xpath("//iframe[#title='recaptcha challenge']");
WebElement frameElement = driver.findElement(frame);
driver.switchTo.frame(frameElement);
then you can execute your script. Finally, for your script if your captcha form is a button
you
cannot call submit();
you
can call click();
Final Answer:
Also check this: js.executeScript("widgetVerified('TOKEN');");
To find the function called widgetVerified() please run this code in the console.
___grecaptcha_cfg.clients[0]
this will return a json, inside of that json try to find the callback function in #Awais case it was wigdetVerified(e)
Warn : Don't use any adblocker

Related

Unable to select/click second and last element on mouse hover in selenium

Below is the screenshot of the mouse hover event.
Style type
It is triggered only on mouse hover. Currently, I'm able to read the Style Type Text. I can select the first element without any issues, however, I'm unable to click the second and last element (Categorized and Graduated ).
UI Code for reference.
UI code
Below is the Selenium code for reference.
static void styletype() throws InterruptedException {
Thread.sleep(1000);
String sname = null;
// select style type
Actions action = new Actions(driver);
WebElement menu = driver.findElement(By.xpath("//*[#src = 'assets/images/down_arrow.svg']"));
action.moveToElement(menu).perform();
Thread.sleep(1500);
List<WebElement> rowsList = driver.findElements(By.xpath("//*[contains(#class,'dropdown-item')]"));
for (WebElement element : rowsList) {
try {
sname = element.getText();
// System.out.println("File Type is : " + sname);
int result = JOptionPane.showConfirmDialog(frame, "Layer Stype Type : '" + sname + "'",
"Do you want to continue", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == 0) {
element.click();
break;
}
action.moveToElement(menu).perform();
Thread.sleep(1000);
} catch (Exception e) {
}
}
}

NotesException: A required argument has not been provided

My XPage gathers information which I use to populate a document in a different Domino database. I use a link button (so I can open another XPage after submission). The onClick code is as follows:
var rtn = true
var util = new utilities()
var hostURL = configBean.getValue("HostURL");
var userAttachment;
//set up info needed for checking duplicates
var attachName=getComponent("attachmentIdentifier").getValue();
var serialNbr = getComponent("serialNumber").getValue();
userAttachment = user+"~"+attachName;
var userSerial = user+"~"+serialNbr;
//Done setting info needed
//check for duplicates
rtn = utilBean.checkAttachmentName(userAttachment, userSerial)
//done
if(rtn==true){
var doc:Document = document1;
dBar.info("ALL IS GOOD");
var noteID:String=document1.getNoteID();
dBar.info("Calling saveNewAttachment using NoteID " + noteID )
rtn=utilBean.saveNewAttachment(session,noteID ); //<<< I get error here
dBar.info("rtn = " + rtn)
return "xsp-success";
view.postScript("window.open('"+sessionScope.nextURL+"')")
}else if (rtn==false){
errMsgArray = utilBean.getErrorMessages();
for(err in errMsgArray){
//for (i=0; i < errMsgArray.size(); i++){
dBar.info("err: "+ err.toString());
if (err== "nameUsed"){
//send message to XPXage
facesContext.addMessage(attachmentIdentifier.getClientId(facesContext) , msg(langBean.getValue("duplicateName")));
}
if(err=="serialUsed"){
//send message to XPXage
facesContext.addMessage(serialNumber.getClientId(facesContext) , msg(langBean.getValue("duplicateSerial")));
}
}
return "xsp-failure";
}
And the java code that delivers the error is this
public boolean saveNewAttachment(Session ses, String noteID)
throws NotesException {
debugMsg("Entering saveNewAttachment and NOTEID = "+noteID);
// this is used when the user saves an attachment to to the
// user profiles db
boolean rtn = false;
Document doc;
ConfigBean configBean = (ConfigBean)
ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(),
"configBean");
String dbName = (String) configBean.getValue("WebsiteDbPath");
debugMsg("A");
Database thisDB = ses.getDatabase(ses.getServerName(), dbName, false);
String value;
try {
debugMsg("noteID: "+noteID);
The next line throws the NotesException error
doc = thisDB.getDocumentByID("noteID");
debugMsg("C");
} catch (Exception e) {
debugMsg("utilitiesBean.saveAttachment: " + e.toString());
e.printStackTrace();
System.out.println("utilitiesBean.saveAttachment: " + e.toString());
throw new RuntimeException("utilitiesBean.saveAttachment: "
+ e.toString());
}
return rtn;
}
I might be going about this wrong. I want to save the document which the data is bound to the User Profile database but if I submit it I need to redirect it to a different page. That is why I am using a link, however, I am having a hard time trying to get the document saved.
Has document1 been saved before this code is called? If not, it's not in the backend database to retrieve via getDocumentByID().
I'm assuming this line has been copied into here incorrectly, because "noteID" is not a NoteID or a variable holding a NoteID, it's a string.
doc = thisDB.getDocumentByID("noteID");

WebDriver prints wrong conditional statement

I'm learning WebDriver and just trying to check the links on demoaut website. The code in the loop is supposed to recognize "Under Construction" page by its title, print out the first line, and then go back to base url. But that doesn't happen for some reason. The very first "under construction" link it gets to (featured vacation destinations) is not recognized as such, prompts the wrong line to be printed, and then instead of going back it crashes due to NoSuchElementException since it's looking for a link on the wrong page. Why is this happening? Why doesn't it act based on the title of "Under Construction" page?
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class CheckLinks {
public static void main(String[] args) {
String baseUrl = "http://newtours.demoaut.com/";
System.setProperty("webdriver.gecko.driver", "C:\\Workspace_e\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
String underConsTitle = "Under Construction: Mercury Tours";
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(baseUrl);
List<WebElement> linkElements = driver.findElements(By.tagName("a"));
String[] linkTexts = new String[linkElements.size()];
int i = 0;
//extract the link texts of each link element
for (WebElement e : linkElements) {
linkTexts[i] = e.getText();
i++;
}
//test each link
for (String t : linkTexts) {
driver.findElement(By.linkText(t)).click();
if (driver.getTitle().equals(underConsTitle)) {
System.out.println("\"" + t + "\""
+ " is under construction.");
} else {
System.out.println("\"" + t + "\""
+ " is working.");
}
driver.navigate().back();
}
driver.quit();
}
}
After you click the first link, all the references in linkTexts will become stale... even if you return to the page. What you need to do is to store all the hrefs in a List and then navigate to each one and check the title of the page.
I would write it this way...
public class CheckLinks
{
public static void main(String[] args) throws UnsupportedFlavorException, IOException
{
String firefoxDriverPath = "C:\\Users\\Jeff\\Desktop\\branches\\Selenium\\lib\\geckodriver-v0.11.1-win32\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", firefoxDriverPath);
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
String baseUrl = "http://newtours.demoaut.com/";
driver.get(baseUrl);
List<WebElement> links = driver.findElements(By.tagName("a"));
List<String> hrefs = new ArrayList<>();
for (WebElement link : links)
{
hrefs.add(link.getAttribute("href"));
}
System.out.println(hrefs.size());
String underConsTitle = "Under Construction: Mercury Tours";
for (String href : hrefs)
{
driver.get(href);
System.out.print("\"" + href + "\"");
if (driver.getTitle().equals(underConsTitle))
{
System.out.println(" is under construction.");
}
else
{
System.out.println(" is working.");
}
}
driver.close();
driver.quit();
}
}
Your code works fine in my Chrome browser. Your problem could be the speed of the webdriver. You can use WebDriverWait which is an explicit wait for a particular element.
Try below modified code
for (String t : linkTexts) {
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.linkText(t))));
driver.findElement(By.linkText(t)).click();
if (driver.getTitle().equals(underConsTitle)) {
System.out.println("\"" + t + "\""
+ " is under construction.");
} else {
System.out.println("\"" + t + "\""
+ " is working.");
}
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
driver.navigate().back();
}
I am able to get the out as below
"Home" is working.
"Flights" is working.
"Hotels" is under construction.
"Car Rentals" is under construction.
"Cruises" is working.
"Destinations" is under construction.
"Vacations" is under construction.
"SIGN-ON" is working.
"REGISTER" is working.
"SUPPORT" is under construction.
"CONTACT" is under construction.
"your destination" is under construction.
"featured vacation destinations" is under construction.
"Register here" is working.
"Business Travel # About.com" is working.
"Salon Travel" is working.
I do not find anything wrong in your logic.Infact I copied your code and just replaced firefox driver with IE driver and it worked as expected.Below was the console output I got on running the code:
> Home" is working. "Flights" is working. "Hotels" is under
> construction. "Car Rentals" is under construction. "Cruises" is
> working. "Destinations" is under construction. "Vacations" is under
> construction. "SIGN-ON" is working. "REGISTER" is working. "SUPPORT"
> is under construction. "CONTACT" is under construction. "your
> destination" is under construction. "featured vacation destinations"
> is under construction. "Register here" is working. "Business Travel #
> About.com" is working.

How to safely use Google translate in Selenium

I am into a project which requires translating text from different languages to English . In a day , I would have to translate nearly 5000 documents.I have written a small selenium code that would help me translate these documents.
Now my question is that if i use Selenium for translating a huge data from google translate ,will I be blocked by Google . If yes , what is the solution to avoid being blocked by Google Translate ?
I have posted my code below for reference :
public static WebDriver google_translate(WebDriver driver,String filename)
{
driver.manage().timeouts().implicitlyWait(5
, TimeUnit.SECONDS);
try{
driver.get("http://translate.google.com/#auto/en");
String text="";
text=read_contents.read_from_html(filename);
if(text.length()<5)
return driver ;
// Enter the query string "Cheese"
System.out.println("file read");
WebElement query = driver.findElement(By.id("source"));
query.sendKeys(text);
WebElement query1 = driver.findElement(By.id("gt-submit"));
query1.click();
System.out.println("text entered");
Date d=new Date();
long intial=d.getTime();
WebElement result;
do{
result = driver.findElement(By.id("result_box"));
d=new Date();
}while(result.getText().length()<20 && (d.getTime()-intial<15000) );
System.out.println("result fetched");
String output=Global.prop.get(1).toString()+"/"+new File(filename).getName()+".txt";
output_writer.txt_writer(result.getText(),output);
}
catch(UnhandledAlertException e)
{
e.printStackTrace();
}
catch(NoSuchElementException e)
{
e.printStackTrace();
}
catch(UnknownServerException e)
{
e.printStackTrace();
}
//System.out.println(result.getText());
return driver ;

Get Attributes of a Hidden Element

I have a table I am trying to test. Inside one of the columns is yes/no radio buttons which when the page is rendered is hidden underneath an image so that there is a check-mark or an X when yes or no is selected.
The attribute for the radio button when yes is selected checked="true".
How do I with Selenium2 get that attribute so that I can compare it or make assertions against it?
I have tried the following, which simply results in a null pointer error.
private void verifyPOEligibleYesNull(String driverName)
{
int min = 1;
int max = 6;
JavascriptExecutor js = (JavascriptExecutor)driver;
StringBuilder stringBuilder = new StringBuilder();
//Navigate to System Facing
driver = browser.getDriver(driverName);
driver.manage().window().maximize();
driver.navigate().to("http://theURL");
//Enter userName
WebElement userName = driver.findElement(By.id("username"));
userName.clear();
userName.sendKeys(user);
//Enter Password
WebElement password = driver.findElement(By.id("pword"));
password.clear();
password.sendKeys(pwd);
//Click Login
WebElement loginBtn = driver.findElement(By.xpath("/html/body/div/div/form/div[3]/div/input"));
loginBtn.click();
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
WebElement ivToPoBtn = driver.findElement(By.xpath("/html/body/div/div/div/ul/li/a/img"));
ivToPoBtn.click();
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Grab a random row and determine whether the PO Eligible is "Yes"
String rowNum = Integer.toString(rand.nextInt(max - min + 1) + min);
WebElement randomRow = driver.findElement(By.xpath("/html/body/div/div/div/div/form/div/div[2]/div/div[2]/div/div/div/div/div/div/div/table/tbody/tr["+rowNum+"]/td/div/div/input"));
String poEligibleChecked = randomRow.getAttribute("checked").toString();
stringBuilder.append("var x = $(\""+poEligibleChecked+"\");");
stringBuilder.append("return x.toString();");
String res = (String) js.executeScript(stringBuilder.toString());
System.out.println(res);
}
I have even tried the following which was suggested from WebDriver FAQ:
WebElement randomRow = driver.findElement(By.xpath("/html/body/div/div/div/div/form/div/div[2]/div/div[2]/div/div/div/div/div/div/div/table/tbody/tr["+rowNum+"]/td/div/div/input"));
String poEligibleChecked = randomRow.getAttribute("checked");
String element = js.executeScript("return arguments[0].getText();", poEligibleChecked).toString();
System.out.println(element);
With similar null pointer exception error.
Your code doesn't really make sense. In order to get the checked attribute of an invisible element, simply use element.getAttribute():
final String scriptGetChecked = "return arguments[0].getAttribute('checked')";
WebElement randomRow = driver.findElement(By.whatever("something"));
String checkedState = (String) js.executeScript(scriptGetChecked, randomRow);

Categories