简体   繁体   中英

Href attribute empty when selecting anchor with xpath

I have a number of links in a page that look like so :

<a class="plant_detail_link" href="plants/O7-01111"><h3>O7-01111</h3></a>

I can select all these link in my page with the following xpath :

//a[@class='plant_detail_link']

I can extract attributes like the class of each link in the usual manner :

//a[@class='plant_detail_link']/@class

But when I attempt to use the same technique to extract the href attribute values I get an empty list :

//a[@class='plant_detail_link']/@href

Does anyone have any ideas why this may be the case?

image detailing chrome developer console xpath execution

EDIT:

See full page html here - http://pastebin.com/MAjTt86V

it's a chrome bug, I believe. You can add the [index].value to get the result. In other words, the $x for href did work but it doesn't return the result in the output for some reason.

For example, I ran these $x queries in the console on this page for the 'Questions' button and got the following output:

$x("//a[@id='nav-questions']/@href")
> []
$x("//a[@id='nav-questions']/@href")[0].value
> "/questions"

You can use something like this to get a usable array of values:

var links = $x("//a[@target='_blank']/@href");
var linkArr = []; 
for (i in links) { linkArr.push(links[i].value)}

or to put it in a function:

function getHref(selector, value, $x) {
var links = $x("//a[@"+selector+"='"+value+"']/@href");
var linkArr = []; 
for (i in links) { linkArr.push(links[i].value)}; 
return linkArr; }

getHref("target","_blank", $x);

EDIT Not sure if this will help you but in chrome adding a comma like this returns the output without the [index].value:

$x,("//a[@id='nav-questions']/@href")
> "//a[@id='nav-questions']/@href"

you could try adding a comma to the xpath selector but I'm not sure if it will help in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM