简体   繁体   中英

Get attribute values matching xpath

Consider the following sample HTML:

<html>
    <head></head>
    <body>
        <a href="link1.html">link1</a>
        <a href="link2.html">link2</a>
    </body>
</html>

$x('/html/body/a/@href') in the Chrome developer console gives me two results: 在此处输入图像描述

Now instead of just matching href , I want to extract the attribute values of href , so the result I want is an array ["link1.html", "link2.html"] . How can I do that?

You can't get an attribute's value directly using xPath , you'll need, after getting the href , to loop over them to get each value

$x('/html/body/a/@href')[0].value
$x('/html/body/a/@href')[1].value

Something like this:

$x('/html/body/a/@href').map(x => x.value)

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