我想将一个从wikipedia的表放入XML文件中,然后将其解析为C#。是否可以?如果是,我可以仅保存XML title 和 genre column?
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load("http://en.wikipedia.org/wiki/2012_in_film");
HtmlNode node = doc.DocumentNode.SelectSingleNode("//table[@class='wikitable']");
您可以使用Web浏览器:
//First navigate to your address
webBrowser1.Navigate("http://en.wikipedia.org/wiki/2012_in_film");
List<string> Genre = new List<string>();
List<string> Title = new List<string>();
//When page loaded
foreach (HtmlElement table in webBrowser1.Document.GetElementsByTagName("table"))
{
if (table.GetAttribute("className").Equals("wikitable"))
{
foreach (HtmlElement tr in table.GetElementsByTagName("tr"))
{
int columncount = 1;
foreach (HtmlElement td in tr.GetElementsByTagName("td"))
{
//Title
if (columncount == 4)
{
Title.Add(td.InnerText);
}
//Genre
if (columncount == 7)
{
Genre.Add(td.InnerText);
}
columncount++;
}
}
}
}
现在您有两个列表(类型和标题)。您只需将它们转换为XML文件
您可以使用此代码:搜索您要搜索的HTML标签并进行正则表达式以解析其余数据。此代码将搜索具有宽度150并获取所有URL/NAV URL的表。
HtmlElementCollection links = webBrowser1.Document.GetElementsByTagName("table"); //get collection in link
{
foreach (HtmlElement link_data in links) //parse for each collection
{
String width = link_data.GetAttribute("width");
{
if (width != null && width == "150")
{
Regex linkX = new Regex("<a[^>]*?href="(?<href>[\s\S]*?)"[^>]*?>(?<Title>[\s\S]*?)</a>", RegexOptions.IgnoreCase);
MatchCollection category_urls = linkX.Matches(link_data.OuterHtml);
if (category_urls.Count > 0)
{
foreach (Match match in category_urls)
{
//rest of the code
}
}
}
}
}
}
还考虑在Wikipedia页面的特定部分中查看Wikipedia API
- https://en.wikipedia.org/w/api.php?action = parse = parse&page=2012_in_film&mobileformat = html&section = 1&amp; prop = wikite =
API文档描述了如何格式化搜索结果以进行后续解析。