3

i am using this code but it returns me the name of the image name with the url

IWebElement element = driver.FindElement(By.XPath("Your xpath"));
string path = element.GetAttribute("src");

result:

http://nameofthehost/imagename.jpg

what i would like is just to spit me the src name, how would i do that?

Nick Kahn
  • 19,652
  • 91
  • 275
  • 406

2 Answers2

5

Some browsers return the full URL in JavaScript, even if a relative URL is specified in the HTML source. So that you don't have to special-case your code based on the browser you're using WebDriver normalizes all properties and attributes that contain URLs to return the full URL. To solve the problem, you can use JavaScript directly.

// assume driver is a valid WebDriver object
// Java code
WebElement element = driver.findElement(By.xpath("your XPath"));
String src = ((JavascriptExecutor)driver).executeScript("return arguments[0].attributes['src'].value;", element).toString();
JimEvans
  • 27,201
  • 7
  • 83
  • 108
  • Thanks I will give a shot and since you are the core contributor to Selenium would you answer this question please? http://stackoverflow.com/questions/12151958/login-popup-window-using-selenium-webdriver – Nick Kahn Sep 06 '12 at 14:48
  • @JimEvans - Thanks for your answer, it solved my problem too, i am getting complete src name, i want only the text/value displayed in the image source. Can you give me any resolution for getting on the value displayed on the image. please find the string i retrieved from the code. "QuickApp/HumanValidationImage.aspx?tid=LZhU3a". But i want only the value "LZhU3a"(Auto Generated). Help will be appreciated – Umamaheshwar Thota Feb 06 '13 at 07:24
  • @UmamaheshwarThota to extract the value you need, use following code: scrID = "QuickApp/HumanValidationImage.aspx?tid=LZhU3a" scrID = scrID.substring(scrID.lastIndexOf('=') + 1); just fit it to your needs. – Michal Oct 22 '13 at 10:47
  • @Siemic -- Thanks for the response. My issue resolved long back. I have split the string as per my requirements and solved the problem. – Umamaheshwar Thota Oct 22 '13 at 11:13
1

In Generalized Form

WebElement element = driver.findElement(locator);
String src = element.getAttribute(src);
String [] srcs=src.split("\");
Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
user3487861
  • 340
  • 2
  • 2