Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath Query: get attribute href from a tag

I want to use XPath to get the href attribute from an a-tag, but it has two occurrences within the same file. How am I getting along? I need to check IF there is an href attribute with value $street/object, I have got this code and it does not work:

$product_photo     = $xpath->query("//a[contains(@href,'{$object_street}fotos/')][1]");         $product_360       = $xpath->query("//a[contains(@href,'{$object_street}360-fotos/')][1]");         $product_blueprint = $xpath->query("//a[contains(@href,'{$object_street}plattegrond/')][1]");         $product_video     = $xpath->query("//a[contains(@href,'{$object_street}video/')][1]"); 

It does not return anything at all. Who can help me out?

like image 325
user3239713 Avatar asked Jan 30 '14 11:01

user3239713


People also ask

How do I find the XPath of a tag?

Go to the First name tab and right click >> Inspect. On inspecting the web element, it will show an input tag and attributes like class and id. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.

Where is XPath for href link in selenium?

This will get you the generic link: selenium. FindElement(By. XPath("xpath=//a[contains(@href,'listDetails.do')")).


1 Answers

For the following HTML document:

<html>   <body>     <a href="http://www.example.com">Example</a>      <a href="http://www.stackoverflow.com">SO</a>    </body> </html> 

The xpath query /html/body//a/@href (or simply //a/@href) will return:

     http://www.example.com     http://www.stackoverflow.com 

To select a specific instance use /html/body//a[N]/@href,

     $ /html/body//a[2]/@href     http://www.stackoverflow.com 

To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:

     $ /html/body//a[contains(@href,'example')]/@href     http://www.example.com 

Mixing the two:

     $ /html/body//a[contains(@href,'com')][2]/@href     http://www.stackoverflow.com 
like image 167
mockinterface Avatar answered Oct 20 '22 22:10

mockinterface