You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术求助:如何编写Xpath获取关联含item前缀id元素的href链接

Let's break down why your link XPath isn't working and get you the correct href values:

The Problem with Your Current XPath

Your existing link code uses:

var Links= doc.DocumentNode.SelectNodes("//a[contains(@id, 'item')]/@href");

This tries to select <a> tags that themselves have an ID containing "item", but looking at your HTML structure:

<li id="item5d86882c07" ...>
<div class="lvpicinner full-width picW">
<a href="https://www.ebay.com/itm/..." class="img imgWr2">

The ID with "item" is on the parent <li> element, not the <a> tag itself. That's why your XPath returns nothing!

Correct XPath Options

Here are two reliable ways to target the right href attributes:

1. Exact Structure Match (Most Precise)

This follows the exact HTML hierarchy you provided, ensuring you only get the image/listing link inside the lvpicinner div:

var links = doc.DocumentNode.SelectNodes("//li[contains(@id, 'item')]/div[@class='lvpic pic img left']/div[@class='lvpicinner full-width picW']/a/@href");

2. Simplified Match (Works if Each Item Has Only One Link)

If every <li> with an "item" ID only has one <a> tag (the listing link), you can use a shorter XPath:

var links = doc.DocumentNode.SelectNodes("//li[contains(@id, 'item')]//a/@href");

The // after the <li> tells XPath to look for any <a> tag nested anywhere inside that list item.

How to Use the Correct XPath

Here's a complete code snippet to retrieve and iterate over the links:

// Assuming you're using HtmlAgilityPack
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(yourHtmlContent); // Or load from a web request

var links = doc.DocumentNode.SelectNodes("//li[contains(@id, 'item')]//div[@class='lvpicinner full-width picW']/a/@href");

if (links != null)
{
    foreach (HtmlAttribute hrefAttr in links)
    {
        string itemLink = hrefAttr.Value;
        // Do something with the link, like add to a list
        Console.WriteLine(itemLink);
    }
}
else
{
    Console.WriteLine("No links found!");
}

Bonus: Align with Your Existing Name XPath

You mentioned your name XPath works: //[contains(@id,'item')]/ul[1]/li1]/span (note: likely a typo, should be li[1]). To keep consistency, you can structure the link XPath to start from the same <li> element, just like your name selector does.

内容的提问来源于stack exchange,提问作者Adil Yar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:43:05