我是C#的新手,所以这可能非常明显,如何让这个工作或对我来说太复杂,但我正在尝试使用HtmlAgilityPack设置和抓取网页。目前我的代码编译但是当我写字符串时我只得到1个结果,它恰好是ul中li的最后一个结果。字符串拆分的原因是我最终可以将标题和描述字符串输出到.csv中以供进一步使用。我只是不确定下一步该做什么,为什么我要求提供任何帮助/理解/想法/想法/建议。谢谢!
private void button1_Click(object sender, EventArgs e)
{
List<string> cities = new List<string>();
//var xpath = "//h2[span/@id='Cities']";
var xpath = "//h2[span/@id='Cities']" + "/following-sibling::ul[1]" + "/li";
WebClient web = new WebClient();
String html = web.DownloadString("http://wikitravel.org/en/Vietnam");
hap.HtmlDocument doc = new hap.HtmlDocument();
doc.LoadHtml(html);
foreach (hap.HtmlNode node in doc.DocumentNode.SelectNodes(xpath))
{
string all = node.InnerText;
//splits text between '—', '-' or ' ' into 2 parts
string[] split = all.Split(new char[] { '—', ' ', '-' }, StringSplitOptions.None);
string title;
string description;
int nodeCount;
nodeCount = node.ChildNodes.Count;
if (nodeCount == 2)
{
title = node.ChildNodes[0].InnerText;
description = node.ChildNodes[1].InnerText;
}
else if (nodeCount == 4)
{
title = node.ChildNodes[0].InnerText;
description = node.ChildNodes[1].InnerText + node.ChildNodes[2].InnerText;
}
else
{
title = "Error";
description = "The node cound was not 2 or 3. Check the div section.";
}
System.IO.StreamWriter write = new System.IO.StreamWriter(@"C:\Users\cbrannin\Desktop\textTest\testText.txt");
write.WriteLine(all);
write.Close();
}
}
}
答案 0 :(得分:2)
一个问题是,每次循环都会覆盖输出文件。你可能想这样做:
using (StreamWriter write = new StreamWriter(@"filename"))
{
foreach (hap.HtmlNode node in doc.DocumentNode.SelectNodes(xpath))
{
// do your thing
write.WriteLine(all);
}
}
另外,您是否已单步执行此操作,以查看您的HtmlNode
来电中是否有多个SelectNode
?
最后,我看不到你在title
或description
做了什么。你打算用别的东西吗?