简体   繁体   中英

Why can I do a "contains" call on the class attribute of an element but not other attributes like href with XPath?

I just started looking into XPath but am a little confused on the following.

I'm parsing HTML (using the HTML-Agility-Pack in C# / .NET) and I'm able to call the contains function on the "class" attribute for an HTML element to only select the nodes whose class contains a specific value.

For example, the top answer on this SO: How can I match on an attribute that contains a certain string?

But I'm unable to call the contains function on the "href" attribute of the HTML "a" (hyperlink) element.

For example, it seems like a more complicate solution is needed, as per this SO accepted answer: Xpath get a if href contains part of string

And if I try to use the following XPath code, I get the ArgumentNullException: "Value cannot be null" exception.

//td/a[contains(@href, 'part-of-the-hyperlink')]

This is the relevant part of HTML I'm trying to select:

 <td> <a href="/name/part-of-the-hyperlink"> Hugh Dane </a> </td>

What am I missing?

Change

//td/a[contains(href, 'part-of-the-hyperlink')]

to

//td/a[contains(@href, 'part-of-the-hyperlink')]

to test the attribute , href , otherwise you're testing the href child element (which doesn't exist).

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