【发布时间】:2017-04-22 05:54:19
【问题描述】:
我想创建一个表,其中 ff.会显示,但我遇到了一些问题
public class Book
{
public HtmlAttribute Href{ get; set; }
public string Title{ get; set; }
public string Author{ get; set; }
public string Characters{ get; set; }
}
这是我要解析的页面,我需要 href 值、 链接、说明和 字符列表(有时没有):
<div id=title>
<li>
<h3><a href="www.harrypotter.com">Harry Potter</a></h3>
<div>Harry James Potter is the title character of J. K. Rowling's Harry Potter series. </div>
<ul>
<li>Harry Potter</li>
<li>Hermione Granger</li>
<li>Ron Weasley</li>
</ul>
</li>
<li>
<h3><a href="www.littleprince.com">Little Prince</a></h3>
<div>A little girl lives in a very grown-up world with her mother, who tries to prepare her for it. </div>
</li>
</div>
这是我的代码来解析它并把它放在一个列表中
List<Book> BookList= new List<Book>();
var titleNode = doc.DocumentNode.SelectNodes("//*[@id=\"title\"]//li//h3");
var descNode = doc.DocumentNode.SelectNodes("//*[@id=\"title\"]//li//div");
var authorNode = doc.DocumentNode.SelectNodes("//*[@id=\"title\"]//li//ul");
var title = titleNode.Select(node => node.InnerText).ToList();
var desc = descNode.Select(node => node.InnerText).ToList();
var characters= authorNode.Select(node => node.InnerText).ToList();
for (int i = 0; i < Title.Count(); ++i)
{
var list= new Book();
list.Title= title[i];
list.Author= desc[i];
list.Characters = characters[i];
BookList.Add(list);
}
我的问题是:1)我将如何获取 href 值并将其添加到列表中? 2) 有些在 html 中没有字符标签,我怎样才能在没有 NullReferenceException 错误的情况下获取列表?注意:我无法对 html 进行任何更改。
【问题讨论】:
标签: c# parsing html-parsing html-agility-pack