用HTML敏捷包C解析HTML标签的问题#
这看起来应该是一件容易的事情,但我遇到了一些重大问题。我正试图解析HAP的特定标签。我使用Firebug来查找我想要的XPath,并拿出// * [@ id =“atfResults”]。我相信我的问题是用“因为信号的开始和一个新的字符串的结束时,我曾试图使其文字字符串,但我有错误,我重视的功能用HTML敏捷包C解析HTML标签的问题#
public List<string> GetHtmlPage(string strURL)
{
// the html retrieved from the page
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(strURL);
objResponse = objRequest.GetResponse();
// the using keyword will automatically dispose the object
// once complete
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{//*[@id="atfResults"]
string strContent = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
/*Regex regex = new Regex("<body>((.|\n)*?)</body>", RegexOptions.IgnoreCase);
//Here we apply our regular expression to our string using the
//Match object.
Match oM = regex.Match(strContent);
Result = oM.Value;*/
HtmlDocument doc = new HtmlDocument();
doc.Load(new StringReader(strContent));
HtmlNode root = doc.DocumentNode;
List<string> itemTags = new List<string>();
string listingtag = "//*[@id="atfResults"]";
foreach (HtmlNode link in root.SelectNodes(listingtag))
{
string att = link.OuterHtml;
itemTags.Add(att);
}
return itemTags;
}
}
你可以逃脱它。:
string listingtag = "//*[@id=\"atfResults\"]";
如果你想使用原始字符串,这将是:
string listingtag = @"//*[@id=""atfResults""]";
正如你可以看到,原始字符串没有真正提供这里的好处
。不过,您可以改用:
HtmlNode link = doc.GetElementById("atfResults");
这也将是稍快。
你有没有尝试过这样的:
string listingtag = "//*[@id='atfResults']";
我试过了,当我运行这个程序时,我被要求找到HtmlNode的源文件。 – 2011-03-23 15:24:20
@Joe - 这是一个很好的XPATH语法,但它可能不会选择你所需要的。你可能有错误。请显示确切的异常StackFrame。 – 2011-03-23 15:47:42
我不再收到那个错误,但是我得到了一个“没有设置为对象实例的对象引用”。错误,因为链接是空的。 – 2011-03-23 16:59:45
请解释反对票。 – 2011-03-23 14:29:12
我是否用这个替换foreach()中的条件? – 2011-03-23 14:32:31
@Joe,你根本不需要循环,因为一个文档只能有一个给定id的元素。 – 2011-03-23 14:46:20