【发布时间】:2018-11-06 03:47:28
【问题描述】:
我刚刚开始遍历 XML 文档来学习如何使用 xpath。
我偶然发现了一个问题。每次我尝试执行我的 xpath 时,它都会返回 null,就好像它没有找到任何东西一样。
我已经在 XMLQuire 中尝试了 xpath,它在那里工作。
class Program
{
private static string URL = "https://www.kijiji.ca/b-renovation-contracting-handyman/ontario/home-renovations/k0c753l9004";
private static HtmlWeb client = new HtmlWeb();
static void Main(string[] args)
{
var DOM = client.Load(URL); // //table/tbody/tr/td[@class = 'description']/p
var Featured = DOM.DocumentNode.SelectNodes("//table[contains(@class,'top-feature')]/tbody/tr/td/a");
foreach (var Listing in Featured)
{
}
}
}
我注释掉了我尝试过的另一个 xpath,我已经尝试了这两个并且都返回 null 为什么会这样?
<table class="top-feature js-hover" data-ad-id="1299717863" data-vip-url="/v-renovation-contracting-handyman/sudbury/c-l-contracting-any-job-big-or-small/1299717863">
<tbody><tr>
<td class="watchlist">
<div class="watch js-hover p-vap-lnk-actn-addwtch" data-action="add" data-adid="1299717863" title="Click to add to My Favourites"><div class="icon"></div></div>
<input id="watchlistXsrf" name="ca.kijiji.xsrf.token" value="1527418405414.9b71d1309fdd8a315258ea5a3dac1a09e4a99ec7f32041df88307c46e26a5b1b" type="hidden">
</td>
<td class="image">
<div class="multiple-images"><img src="https://i.ebayimg.com/00/s/NjAwWDgwMA==/z/fXEAAOSwaZdZxTv~/$_2.JPG" alt="C.L. Contracting. Any job big or small."></div>
</td>
<td class="description">
<a href="/v-renovation-contracting-handyman/sudbury/c-l-contracting-any-job-big-or-small/1299717863" class="title ">
C.L. Contracting. Any job big or small.</a>
<p>
Contractor handyman home renovations and repairs. Contractor for Dollarama, Rexall, LaSenza and more. Fully licensed and insured. Able to do drywall, decks, framing, plumbing, flooring windows, ...</p>
<p class="details">
</p>
</td>
<td class="posted">
</td>
</tr>
</tbody></table>
我的解决方案(需要帮助将我的 xpath 变成 1 行,而不是用一堆循环遍历。)
private static string URL = "https://www.kijiji.ca/b-renovation-contracting-handyman/ontario/home-renovations/k0c753l9004";
private static HtmlWeb client = new HtmlWeb();
static void Main(string[] args)
{
var DOM = client.Load(URL); // //table/tbody/tr/td[@class = 'description']/p
var Featured = DOM.DocumentNode.SelectNodes("//table[contains(@class,'top-feature')]/tbody/tr/td/a");
foreach (var table in DOM.DocumentNode.SelectNodes("//table[contains(@class, 'top-feature')]"))
{
Console.WriteLine($"Found: {table}");
foreach (var rows in table.SelectNodes("tr"))
{
Console.WriteLine(rows);
foreach (var cell in rows.SelectNodes("td[@class='description']/a"))
{
Console.WriteLine(cell.InnerText.Trim());
}
}
}
Console.ReadKey();
我已经设法修复它,但是我一直很好奇为什么这个 xpath 有效
//table[contains(@class, 'top-feature')]/tr/td[@class='description']/a
而这个没有。
//table[contains(@class,'top-feature')]/tbody/tr/td/a
【问题讨论】:
-
您是否尝试在属性值中包含
js-hover? -
我做了,是的,让我更新我的问题,我找到了一个解决方案,但我想知道我是否可以将我的解决方案变成 1 行 xpath 而不是所有这些行
-
@mjwills 我的错!更新了!
-
请将 XML 显示为代码,而不是图片。
-
@choroba 我更新了我的问题,请参阅底部关于为什么新的 xpath 工作而不是旧的工作
标签: c# .net xml xpath html-agility-pack