Scenario:
I open www.google.com, input some keywords and click the search button.
now i get to the result page. I want to get the current url of this result page, including the query parameters.
I found a method getBrowserUrl() here phpunit-selenium on github. Line 410
But this method returned the value which I set in the setUp function.
public function setUp(){
$this->setBrowser(testConfig::$browserName);
$this->setBrowserUrl('http://www.google.com/');
}
public function testGoogleSearch(){
$this->url('');
//input some keywords
.......
//click search button
.......
//want to get the url of result page
$resultUrl= $this->getBrowserUrl();
echo $resultUrl;
}
I got a string 'http://www.google.com/' instead of the whole url of result page.
Please help me,thanks!
The answer is:
$currentURL = $this->url();
I also asked this question here
Thanks to #jaruzafa
From the source code, I'd say it's getCurrentURL()
https://github.com/facebook/php-webdriver/blob/787e71db74e42cdf13a41d500f75ea43da84bc75/lib/WebDriver.php#L43
You can also use
$url=$this->getLocation();
This is how I'll get the current URL
$resultUrl = $this->getSession()->getDriver()->getCurrentUrl();
echo $resultUrl;
or
$resultUrl = $this->getSession()->getCurrentUrl();
echo $resultUrl;
Both are from Behat - Mink
If you are using an older version of PHPUnit Selenium this might be helpful:
$url = $this->getEval('window.location.href;');
$this->assertEquals('EXPECTEDURL', $url);
This is what worked for me
$urlAry = $driver->executeScript('return window.location',array());
$currentURL = $urlAry['href'];
Related
I am new bee of the automation testing. On my code, I am using the JavaScript on my Selenium automation test script (on using the JUnit). I am trying to find the current window title:
driver = new ChromeDriver();
js = (JavaScriptExecutor)driver;
driver.get(//passed url);
//after the log in my Org. I execute the command below
//to get the title of the current window I execute the below command
js.executeScript("document.getElementsByTagName('title').innerHTML;");
But the above command will return the answer as the null instant of
getting the title of the window. So does anyone know what's wrong with
my command?
But I get the title of the window on executing on the console log of the page. So I don't know what's wrong with my code.
Thanks.
Mohan Raj S.
Change the following line:
document.getElementsByTagName('title').innerHTML
to:
return document.getElementsByTagName('title')[0].innerHTML
in code it will be:
js.executeScript("return document.getElementsByTagName('title')[0].innerHTML;");
getElementsByTagName returns array of elements. So we need to pass the index value.
Web driver interface provides get title method. It is very simple.
String title=driver.getTitle();
System.out.println("Title is" + title);
You could do it like this also
function titleCheck() {
promise = driver.getTitle();
promise.then(function(title) {
console.log("The title is: " + title);
});
}
reference: https://blog.testproject.io/2018/03/08/selenium-javascript-best-practices/
though their var test- stuff doesn't work for me I had to remove it.
JavascriptExecutor js = (JavascriptExecutor)driver;
String text = js.executeScript("return document.title;").toString();
I am new to selenium, I am trying to verify if a checkbox is enabled on a page.It does not matter if it is checked or unchecked. I only have to verify that it can be selected i.e it is enabled for usage.
I have the id of the checkbox that is "chkEP". Kindly help. I am using java.
I have found different answers against my query via googling it but they all are verifying if chechbox is checked or not. Many many thanks for the help.
The WebElement interface has an isEnabled method on it. See here.
Otherwise, you can manually check the attribute - See here. Code:
String isDisabled = textlink.getAttribute("disabled");
if (isDisabled==null || !isDisabled.equals("disabled")){
System.out.println("View link: Enabled");
}else{
System.out.println("View link: Disabled");
}
Have you tried isEnabled()??
WebElement we = driver.findElement(By.id(""));
we.isEnabled();
I'd prefer to use the webdriver isEnabled() method.
WebElement element = driver.findElement(By.id("value"));
if (element.isEnabled()) {
//insert your code here
}
Please note that if the element is not present in the web page, noSuchElementException will be thrown in the first line itself.
I am trying to use Selenium's Xpath ability to be able to find an set of elements. I have used FirePath on FireFox to create and test the Xpath that I have come up with and that is working just fine but when I use the Xpath in my c# test with Selenium nothing is returned.
var MiElements = this._driver.FindElements(By.XPath("//div[#class='context-menu-item' and descendant::div[text()='Action Selected Jobs']]"));
and the Html looks like this:-
Can Anyone please point me right as everything that I have read the web says to me that this Xpath is correct.
Thanking you all in-advance.
Please post the actual HTML, so we can simply "drop it in" into a HTML file and try it ourselves but I noticed that there is a trailing space at the end of the class name:
<div title="Actions Selected Jobs." class="context-menu-item " .....
So force XPath to strip the trailing spaces first:
var MiElements = this._driver.FindElements(By.XPath("//div[normalize-space(#class)='context-menu-item' and descendant::div[text()='Action Selected Jobs']]"));
Perhaps you don't take into consideration the time that the elements need to load and you look for them when they aren't yet "searchable". UPDATE I skipped examples regarding this issue. See Slanec's comment.
Anyway, Selenium recommends to avoid searching by xpath whenever it is possible, because of being slower and more "fragile".
You could find your element like this:
//see the method code below
WebElement div = findDivByTitle("Action Selected Jobs");
//example of searching for one (first found) element
if (div != null) {
WebElement myElement = div.findElement(By.className("context-menu-item"));
}
......
//example of searching for all the elements
if (div != null) {
WebElement myElement = div.findElements(By.className("context-menu-item-inner"));
}
//try to wrap the code above in convenient method/s with expressive names
//and separate it from test code
......
WebElement findDivByTitle(final String divTitle) {
List<WebElement> foundDivs = this._driver.findElements(By.tagName("div"));
for (WebElement div : foundDivs) {
if (element.getAttribute("title").equals(divTitle)) {
return element;
}
}
return null;
}
This is approximate code (based on your explanation), you should adapt it better to your purposes. Again, remember to take the load time into account and to separate your utility code from the test code.
Hope it helps.
How to verify whether links are present or not?
eg.
I have 10 links in a page, I want to verify the particular link
Is it possible?
I am using selenium with Java.
Does i can write inside the selenium code
eg
selenium.click("searchimage-size");
selenium.waitForPopUp("dataitem", "3000");
selenium.selectWindow("name=dataitem");
foreach(var link in getMyLinkTextsToTest())
{
var elementToTest = driver.findElement(By.linkText(link));
Assert.IsNotNull(elementToTest);
}
What you can do is find all links on the page like this:
var anchorTags driver.findElement(By.TagName("a"));
and then iterate through the anchorTags collection to make you you've got what you're looking for.
Or if you have a list of the link texts you can do something like this:
foreach(var link in getMyLinkTextsToTest())
{
var elementToTest = driver.findElement(By.linkText(link));
Assert.IsNotNull(elementToTest);
}
This code is all untested and right off the top of my head so you might need to do some slight modification but it should be close to usable.
if you are using Selenium 1.x you can use this code.
String xpath = "//<xpath till your anchor tag>a/#herf";
String href = selenium.getAttribute(xpath);
String expectedLink = "your link";
assertEquals(href,expectedLink);
I hope this may help you...
List<WebElement> links = driver.findElements(By.tagName("a"));
for(WebElement we : links) {
if("Specific link text".equals(we.getText("Specific link text"))) {
we.click();
}
}
I'm taking all links to List variable 'links' and iterating it. Then checking condition, for the specific text we looking in the link is presenting in the list or not. If it found out, it'll click on it
If you're looking to verify each specific for the content of href, you can use javascript to return the outerHTML for a specific Webelement which you can identify however you like; in the example below I use By.cssSelector:
WebElement Element = driver.findElement(By.cssSelector("..."));
String sourceContents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].outerHTML;", element);
assertEquals(sourceContents, "Learn More");
If you want to make it a tad more elegant you can shave the undesired elements off of the string, but this is the general case as of Selenium-java: 2.53.1 / Selenium-api: 2.47.1 as I can observe.
Best approach would be to use getText() method
List<WebElement> allLinks = driver.findElements(By.tagName("a"));
for(WebElement specificlink : allLinks ) {
if(specificlink.getText().equals("link Text"){
//SOPL("Link found");
break;
}
}
I'm using selenium RC and want to get all the attributes and all. Something like:
link = sel.get_full_link('//a[#id="specific-link"]')
and the result would of:
print link
would be:
<a id="specific-link" name="links-name" href="url"> text </a>
Is this possible?
thanks
Here's a fancier solution:
sel.get_eval("window.document.getElementByID('ID').innerHTML")
(don't be picky with me on the javascript..)
I think the best way to do this would be to use the getHtmlSource command to get the entire HTML source, and then use either a regular expression or HTML parser to extract the element of interest.
The following Java example will output all links to System.out:
selenium.open("http://www.example.com/");
String htmlSource = selenium.getHtmlSource();
Pattern linkElementPattern = Pattern.compile("<a\\b[^>]*href=\"[^>]*>(.*?)</a>");
Matcher linkElementMatcher = linkElementPattern.matcher(htmlSource);
while (linkElementMatcher.find()) {
System.out.println(linkElementMatcher.group());
}
getAttribute
String href = selenium.getAttribute("xpath=//a[#id="specific-link"]/#href")
I've been trying to do just this, and came up with the following:-
var selenium = Selenium;
string linkText = selenium.GetText("//a[#href='/admin/design-management']");
Assert.AreEqual("Design Management", linkText);
use below code to get all the links on the page:
$str3= "window.document.getElementsByTagName('a')";
$k = $this->selenium->getEval($str3);
$url = explode(",",$k);
$array_size = count($url);
$name=array();
$l=0;
for($i=0;$i<$array_size;$i++)
{
if(!strstr($url[$i], 'javascript'))
{
$name[$l]=$url[$i];
echo "\n".$name[$l];
$l++;
}
}
If the link isn't dynamic, then try this rather cheesy, hacky solution (This is in Python):
selenium.click("//a[text()='Link Text']")<br>
selenium.wait_for_page_to_load(30000)<br>
myurl = selenium.get_location()
Cheesy but it works.
Note: this will not work if the link redirects.