Selenium Webdriver, Javascript link, Unable to locale Element - java

Hi I am facing this issue, Below is a code which i had generated using Selenium IDE, Basically i am trying to access a career portal of the particular website below and for the Jobposting QA specialist, I was experimenting to auto complete the application using Selenium.
1) I am not able to replicate the code working in webdriver despite adding the code under proper class and importing all the necessary packages.
2) On running it as a TestNG test, i have a failure showing Unable to find Element.
3) The link to the QA specialist is not being detected by the driver either if i give it as identify By.link text or By.xpath.
4) please guide me where i am making mistake.
5) I am a beginer to Selenium
public class Application {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.saymedia.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testApplication() throws Exception {
driver.get(baseUrl + "/jobs");
driver.findElement(By.linkText("QA Specialist")).click();
driver.findElement(By.linkText("Apply Now")).click();
driver.findElement(By.linkText("Send Application")).click();
}

Your elements are inside of an iframe. Selenium only interacts with elements in the current frame. Any element within a child frame cannot be interacted with until you switch into that frame. You can switch by using switchTo().frame():
driver.get(baseUrl + "/jobs");
driver.switchTo().frame("jobviteframe");
driver.findElement(By.linkText("QA Specialist")).click();
driver.findElement(By.linkText("Apply Now")).click();
driver.findElement(By.linkText("Send Application")).click();
The arguments for frame() are
number from 0
id of the frame
the webelement rerference of the frame
When done in the iframe, use the following to exit back to the top of the document:
driver.switchTo().defaultContent();

Related

Not able to locate an element within the IFrame (Selenium)

So i have create successful test of adding a card to my profile and now i would like ot verify if card was added so i would like to check if "Your card was successfully added" text appeared, however for some kind of a reason the className not located.
This is an iframe however i do enter it to add the card details and submit them, so trying to understand why it cant locate the follow:
Adding card
public void addCard(Card card) {
switchToCardIframe()
.fillInCardNumber(card.getCardNumber())
.fillInCardHolder(card.getCardHolderName())
.fillInExpiryDate(card.getExpiryDate())
.fillInCvv(card.getCvv())
.clickOnToggle()
.clickOnAddButton();
}
This is how i locate the text
#FindBy(css = "payment-state-message")
private WebElement cardAddedIndicator;
Test
#Test
public void shouldSuccessfullyAddCard() {
myCards.addCard(cardData());
assertTrue(myCards.getCardAddedIndicator().isDisplayed());
}
I have also tried to check if another element displayed by escaping the iframe but no luck so any help appreciated
driver.switchTo().defaultContent()
I have also attempted Thread.sleep() for 10 seconds before taking getting the text from the css locater but not luck
Here is the base page where wait initialized
public class BasePage {
public WebDriver driver;
protected Wait wait;
public BasePage(WebDriver driver) {
initializePage(driver);
this.wait = new Wait(driver);
}
final protected void initializePage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(new AjaxElementLocatorFactory(driver, 20), this);
}
}
Your css is wrong, so instead of
#FindBy(css = "payment-state-message")
private WebElement cardAddedIndicator;
try this
#FindBy(css = ".payment-state-message")
private WebElement cardAddedIndicator;
also do not check for visibility by .isDisplay
rather have a text method called on it. Put some delay/wait as well.
String actualMessage = myCards.getCardAddedIndicator().getText();
String expectedMessage = "Your card was successfully added"
then assert these two based on their actual and expected behavior .
Conclusion :
When there is an iframe form and you submit it, it does not mean that its still the same iframe. In my case when I submitted the form then iframe disappeared however in order for for the element to be located I had to perform driver().switch().parentFrame()
FYI: First always check your locators and make sure they are right.

Selenium-Java is opening two instances of Firefox

I'm just starting to learn selenium java.
I had this test code, its just basically open google.com page and get its title, and assert the title. my problem is every time I run the test, the Firefox gets called twice. I already search around about the possible issue, tried some of the fix. but nothing works for me.. tried changing "#BeforeTest" to "#BeforeClass" and to "#Before" still the same.
firefox version: 55.0.3
selenium version: 3.5.3
geckodriver : 0.19.0
here's my code:
public class ATest {
public String baseURL = "http://google.com";
public WebDriver driver;
#BeforeTest
public void setBaseURL() {
driver = new FirefoxDriver();
driver.get(baseURL);
}
#Test
public void verifyHomePageTitle() {
setBaseURL();
String expectedTitle = "Google";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
}
}
#BeforeTest executes before tests so You need to remove setBaseURL() from Your test. It will be run before it anyway.
I haven't used Selenium with Java, only with Ruby. But my guess is that #BeforeTest directive makes setBaseURL() to be executed before each test. So here you have your first opened browser. Later when in your actual test what you do is you run setBaseURL() again, which opens second browser.
Remove setBaseURL() from verifyHomePageTitle(), or remove #BeforeTest
get method is called twice hence it loads page twice. Once in #BeforeTest and second in #Test by calling setBaseURL. Remove the setBaseURL from #BeforeTest, move the get method in actual #Test method and you should be fine
Here is what java doc says about get method
void get(java.lang.String url)
Load a new web page in the current browser window.
get
void get(java.lang.String url)
Load a new web page in the current browser window. This is done using an HTTP GET operation, and the method will block until the load is complete. This will follow redirects issued either by the server or as a meta-redirect from within the returned HTML. Should a meta-redirect "rest" for any duration of time, it is best to wait until this timeout is over, since should the underlying page change whilst your test is executing the results of future calls against this interface will be against the freshly loaded page. Synonym for WebDriver.Navigation.to(String).
Parameters: url - The URL to load. It is best to use a fully qualified URL
public class ATest {
public String baseURL = "http://google.com";
public WebDriver driver;
#BeforeTest
public void setBaseURL() {
driver = new FirefoxDriver();
}
#Test
public void verifyHomePageTitle() {
driver.get(baseURL);
String expectedTitle = "Google";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
}
}
Links for reference
Java Doc : http://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/WebDriver.html#get-java.lang.String-

How to get an autocomplete to work with java webdriver?

I have the following selenium automation code that used to work for an autocomplete dropdown:
#FindBy(xpath = "//*[#id='s2id_customer-name-search']/a")
private static WebElement customerDrop;
#FindBy(id = "s2id_autogen5_search")
private static WebElement searchField;
public static void searchByCustomer(String customer) {
customerDrop.click();
new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOf(searchField()));
searchField.sendKeys(customer);
new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOf(searchResult()));
searchResult.click();
}
A change was made to the page in order to resolve an issue with clearing the field, and now the automation no longer autocompletes. Manual entry still triggers the autocomplete, but not with my automation code.
Is there another way to do this that will also trigger the autocomplete?

Generating Java cssSelector to click span element in Selenium

I'm calling IE driver to launch this webpage (Business Objects). I'm able to login with the credentials. I need to click on a element on the next page. Need help writing the java to read this element and click.
<span style="white-space:nowrap;" class="iconText" id="IconImg_Txt_btnListing">Document List</span>
This is what I got so far using firebug-firepath.
driver.switchTo().defaultContent();
pickObj = driver.findElement(By.cssSelector("#IconImg_Txt_btnListing"));
pickObj.click();
Update: Another attempt-
public class InitComp {
//private WebDriver driver;
#FindBy(how = How.CSS, using = "#IconImg_Txt_btnListing") private WebElement DocListBtn;
public void clickDocList() {
DocListBtn.click();
}
}
This class is called as-
InitComp init = new InitComp();
PageFactory.initElements(driver, init);
init.clickDocList();
This does not help either though. Throws me an exception - "ElementNotFound". This page happens to be the first page after login. Where am I going wrong?
Thanks.
Arya

How to verify a page title using WebDriver and page object?

I am trying to write a method to verify page title using page objects but I am unable to do it. Could you please help me out how to write a method to verify page title after searching something in the google page.
Here is my 2 classes.
Class 1
public class GoogleSearchPage {
protected WebDriver driver;
#FindBy(name="q")
private WebElement SearchBox;
#FindBy(name="btnG")
private WebElement SearchButton;
public void SearchFor(String SearchTerm)
{
SearchBox.sendKeys(SearchTerm);
SearchButton.click();
}
}
Class2
public class TestSearchResults {
WebDriver driver;
GoogleSearchPage page;
#BeforeClass
public void Launch() throws Exception
{
driver = new FirefoxDriver();
driver.get("http://google.com");
}
#AfterClass
public void Close()
{
driver.quit();
}
#Test
public void ResultPage() {
System.out.println(page);
page=PageFactory.initElements(driver, GoogleSearchPage.class);
page.SearchFor("selenium");
}
}
Could you please help how to verify the title after displaying the Search results
Note: I am using TestNG.
Thanks in Advance,
Shiva Oleti.
Try this:
assertEquals("Your Page Title" , driver.getTitle());
driver.getTitle() - Returns Title of your current page.
You can get & verify title of page using python webdriver. See below codes
driver.title('title name')
assert 'title name' in driver.title('title name')
It will verify the title name. if it is there title name test case pass else through assert error.
Create a constructor in each page object. The constructor:
sets the instance driver value
waits for page load to complete (e.g. loading spinner not visible, jQuery.active == 0, document.readyState == 'complete')
verifies the page title (see other answers)
Issue PageFactory.initElement(driver, this);
Therefore you don't need a separate method to verify title. In each step you will have a new YourPageObjectPage() which checks the title automatically. Think DRY.

Categories

Resources