How to extract text from second link using previous webelement? - java

I am using this code, but it's not working but xpath in the picture is correct. I am not allowed to use (//h2//a[#class='question-link'])[2] because I need to use previous webelement:
driver.get("https://stackexchange.com/");
WebElement e = driver.findElement(By.xpath("//h2//a[#class='question-link']"));
WebElement f=e.findElement(By.xpath(".[2]"));
System.out.println(f.getText());

The second element you want is just another element that is located by the first locator. The easiest way to do what you are asking is to change the first statement to use .findElements() (plural) and then get the second element returned.
List<WebElement> e = driver.findElements(By.xpath("//h2//a[#class='question-link']"));
System.out.println(e.get(1).getText()); // index starts at 0 so 1 is the second element

Instead of again writing Webelement f write the complete xpath including [2] in Webelement e itself.

Here is an example in Python using Selenium to extract the text from the second link using a previous WebElement:
from selenium import webdriver
initialize the browser
driver = webdriver.Firefox()
navigate to the website
driver.get("https://www.example.com")
locate the previous WebElement
previous_element = driver.find_element_by_css_selector("#element_id")
locate the second link relative to the previous WebElement
second_link = previous_element.find_elements_by_tag_name("a")[1]
extract the text from the second link
text = second_link.text
close the browser
driver.quit()
Note: Replace #element_id with the actual id of the previous WebElement and make sure to install the Selenium library if not already installed.

Related

Selenium webdriver (java) - Click on desired link of some search results

I am doing automation using selenium webdriver (java) on a search engine BookMyCrop (http://www.bookmycrop.com). Here, I searched for a crop but, I am not able to click on desired search result. Please help me with it.
Code :
WebElement search = driver.findElement(By.xpath("//*[#id=\"search_keyword\"]"));
search.sendKeys("59825");
search.sendKeys(Keys.ENTER);
driver.findElement(By.partialLinkText("Cashew")).click();
------My 1st try-------------
//WebElement link = driver.findElement(By.xpath("\"//div[#id = 'Links']/a[3]\""));
//link.click();
------My 2nd try-------------
//List<WebElement> find = driver.findElements(By.xpath("/html/body/section[2]/div[2]/div/div/div/div[1]"));
//find.get(1).click();
}
} –
You can use the css selector based on class names: ".product-block.inner-product-block" and get the list of all the search results.
Then click on whatever index you want to click.
I am not using an IDE for this but it would look something like this:
driver.findElements(By.cssSelector(".product-block.inner-product-block")).get(0).click();
As said, you can try with css ".product-block.inner-product-block"
Then
get List of WebElements
do loop
inside loop, try get text of each element or innerText attribute
cross check if it is required one or not by simple if condition
If so, click on that web element and break loop
if this locator is not giving required info, try other locator. say $$("a h3") for veg names.
The below code worked for me. It is navigates to the correct link
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.bookmycrop.com");
WebElement search = driver.findElement(By.xpath("//*[#id=\"search_keyword\"]"));
search.sendKeys("59825");
search.sendKeys(Keys.ENTER);
driver.findElement(By.partialLinkText("Cashew")).click();

Selenium not able to input element in the form inside fieldset tag

I have tried a different method to input elements like
Here is xpath I used
By NameOfTheProperty=By.xpath("//fieldset/div/input[#name='name']");
By NameOfTheProperty=By.xpath("//div/input[#name='name']");
By NameOfTheProperty=By.xpath("//input[#name='name']");
Tried with Selenium Builder
WebElement element=driver.findElement(by);
Actions builder = new Actions(driver);
Action mouseOverHome = builder
.moveToElement(element)
.click().sendKeys(text).build();
mouseOverHome.perform();
Tried with
WebElement element=driver.findElement(by);
element.sendKeys(text);
None of the methods is working..I can not able to input text inside the field and It shows
Element not interactable
Here is the site
I hope someone help me to find out the solution..
Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.
Steps to check:
Press F12 in Chrome -> go to element section -> do a CTRL + F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.
xpath you should checks is :
//input[#name='name']
if it is unique, then you can use Javascript executor :
WebElement password_input = driver.findElemenet(By.xpath("//input[#name='name']"));
((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('value', 'password_should_be_written_here')", password_input)
personally I would use id's if the element has one.
"//*[#id='__BVID__104']"
Make sure you are waiting for the element to be ready.
WebDriverWait wait = new WebDriverWait();
wait.until(ExpectedConditions.elementToBeClickable(element));
If it then times out on wait.until(... then I've found that sometimes an element must first be clicked for it to be exposed.
If this is the case. You will have to inspect the element before it is clicked. Find it's xpath, and see if it changes when it is clicked. If so then create a webElement for that element and have Selenium first click it, before clicking the actual field/element.

Why no elements can be tergeted on this website?

I'm trying to use selenium to type in data in inputboxes. But I cant get any element (NoSuchElementException). Problem is only with this site.
I tried searching by name/id but it failed.
WebDriver driver = new FirefoxDriver();
driver.get("https://ekrs.ms.gov.pl/web/wyszukiwarka-krs/strona-glowna");
System.out.println(driver.getCurrentUrl());
System.out.println("Successfully opened the website");
WebElement wb = driver.findElement(By.id("rejestrPrzedsiebiorcy"));
My goal (for now) is just to get this element :P.
The problem is the form is included in the source via <iframe> element. You can see that it has attribute src="https://ekrs.ms.gov.pl/krsrdf/krs/wyszukiwaniepodmiotu?". If you go to that link, you will see standalone form. The question is - how to access an included source? It's quite simple ;)
Find the <iframe> element:
WebElement frame = driver.findElement(By.xpath("//div[#class='portlet-body']/div/iframe"))
Switch to that frame:
driver.switchTo().frame(frame)
And that's it! Now you are in the <iframe> element context, and you can search inside it. so this will work now:
WebElement wb = driver.findElement(By.id("rejestrPrzedsiebiorcy"));
To switch back (get out of the frame context) you just have to call:
driver.switchTo().defaultContent();
Note that this site has dynamically generated ids to prevent automation, and uses CaptchaV3 (you can see I used xpath expression to find the iframe). Selenium is easily detectable if you are not careful.
Carefully observe the HTML code after inspecting required element. If you element is inside <iframe> then you need to switch on to frame first and then find that element.
below is the way to switch to frame:
driver.switchTo().frame() method takes one of the three possible arguments:
A number.
Select a frame by its (zero-based) index. That is, if a page has three frames, the first frame would be at index 0, the second at index 1 and the third at index 2. Once the frame has been selected, all subsequent calls on the WebDriver interface are made to that frame.
driver.switchTo().frame(0)
A name or ID.
Select a frame by its name or ID. Frames located by matching name attributes are always given precedence over those matched by ID.
driver.switchTo().frame("name here");
A previously found WebElement.
Select a frame using its previously located WebElement.
WebElement iframeElement = driver.findElement(By.id("IF1"));
//now use the switch command
driver.switchTo().frame(iframeElement);
Try driver.findElement(By.id("form-main")); first, then driver.findElement(By.id("rejestrPrzedsiebiorcy")); again.

Selenium getting text input of Twingly (Java Code)

Please check out the element of this website.
It has a form, and along with 2 text input and 1 submit button.
I dont know which one from those 2 inputs that is actually used when the user type-in some urls over there.
But when I tried this (using firefoxDriver) to get the element:
WebElement textfieldURL = driver.findElement(By.id("ping-url")); // even ping-box not working
The result's unable to locate the element.
Then I change my code to this :
driver.switchTo().frame(driver.findElement(By.className("ping-iframe")));
WebElement textfieldURL = driver.findElement(By.id("ping-url")); // even ping-box not working
The result's still unable to locate the element.
Any clues?
You haven't mentioned the exception which you are facing. As your input tag present under iframe so you need to first switch into frame and than have to perform actions -
driver.switchTo().frame(driver.findElement(By.className("ping-iframe")));
//or you can use frame index as well
driver.switchTo().frame(0);
your element is available with the id ping-box . Try the following complete code -
System.setProperty("webdriver.gecko.driver","D:/Application/geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.twingly.com/ping");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.switchTo().frame(driver.findElement(By.className("ping-iframe")));
driver.findElement(By.id("ping-box")).sendKeys("http://www.google.com");
driver.findElement(By.id("ping-button")).click();
Same is working for me.

How to select options provided in a textbox using Selenium

Link: http://www.bbc.com/weather/
Scenario: Type "reading" on the find a forecast text box. This shows 2 options. How do I select one option using Selenium WebDriver?
I am using the following command to type "reading"
driver.findElement(By.id("locator-form-search")).sendKeys("Reading");
I added explict wait as you suggested and this worked with a small change in the css path. This is what I did:
WebElement suggestedList = new WebDriverWait(driver, 15)
.until(ExpectedConditions.elementToBeClickable(By
.cssSelector("div[class='locator-suggestions locator-suggestions-default'] >ul >li:nth-of-type(1)")));
driver.findElement(
By.cssSelector("div[class='locator-suggestions locator-suggestions-default'] >ul >li:nth-of-type(1)"))
.click();
Use the following locator to click on the first element (first suggestion displayed after typing):
driver.findElement(By.cssSelector("div[class='locator-suggestions locator-suggestions-default'] li:nth-child(1)")).click();
Similarly you can click on the other element by changing the locator. For example to select the second element:
driver.findElement(By.cssSelector("div[class='locator-suggestions locator-suggestions-default'] li:nth-child(2)")).click();
Just to add here, you may need to wait for the elements/suggestions (which you're trying to select) to be visible, before trying to click on those. Use/search for a appropriate wait method for your testing.
So,
first you need to type "reading" in the field as you are doing by using driver.findElement(By.cssSelector("input#locator-form-search")).sendKeys("Reading");
then wait for element to be visible
Then try the above mentioned code to select the desired element.
Hope this helps.

Categories

Resources