C# 用C解析HTML表中的单个数据元素?
我的主函数中有这段代码,我只想解析表的第一行,例如2017年11月7日73.78 74.00 72.32 72.71 17245947 我创建了一个仅包含第一行的节点,但当我开始调试时,节点值为null。如何解析这些数据并将其存储在字符串或单个变量中。有办法吗C# 用C解析HTML表中的单个数据元素?,c#,web-scraping,html-agility-pack,C#,Web Scraping,Html Agility Pack,我的主函数中有这段代码,我只想解析表的第一行,例如2017年11月7日73.78 74.00 72.32 72.71 17245947 我创建了一个仅包含第一行的节点,但当我开始调试时,节点值为null。如何解析这些数据并将其存储在字符串或单个变量中。有办法吗 WebClient web = new WebClient(); string page = web.DownloadString("https://finance.google.com/finance/historic
WebClient web = new WebClient();
string page = web.DownloadString("https://finance.google.com/finance/historical?q=NYSE:C&ei=7O4nV9GdJcHomAG02L_wCw");
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(page);
var node = doc.DocumentNode.SelectSingleNode("//*[@id=\"prices\"]/table/tbody/tr[2]");
List<List<string>> node = doc.DocumentNode.SelectSingleNode("//*[@id=\"prices\"]/table").Descendants("tr").Skip(1).Where(tr => tr.Elements("td").Count() > 1).Select(tr => tr.Elements("td").Select(td=>td.InnerText.Trim()).ToList()).ToList() ;
您的选择XPath字符串似乎有错误。由于tbody是生成的节点,因此不应包含在路径中:
//*[@id=\"prices\"]/table/tr[2]
虽然这应该读取值HtmlAgilityPack,但它遇到了另一个问题,即格式错误的html。解析文本中的所有和节点都没有相应的或结束标记,HtmlAgilityPack无法从格式错误的行中选择值。因此,有必要在第一步选择整个表格:
//*[@id=\"prices\"]/table
在下一步中,或者通过添加和关闭标记来清理HTML,并使用更正的表重复解析,或者使用提取的字符串手动解析—只需从表字符串中提取第10行到第15行,并在>字符上拆分它们。原始解析如下所示。代码经过测试并正常工作
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
namespace GoogleFinanceDataScraper
{
class Program
{
static void Main(string[] args)
{
WebClient web = new WebClient();
string page = web.DownloadString("https://finance.google.com/finance/historical?q=NYSE:C&ei=7O4nV9GdJcHomAG02L_wCw");
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(page);
var node = doc.DocumentNode.SelectSingleNode("//div[@id='prices']/table");
string outerHtml = node.OuterHtml;
List<String> data = new List<string>();
using(StringReader reader = new StringReader(outerHtml))
{
for(int i = 0; ; i++)
{
var line = reader.ReadLine();
if (i < 9) continue;
else if (i < 15)
{
var dataRawArray = line.Split(new char[] { '>' });
var value = dataRawArray[1];
data.Add(value);
}
else break;
}
}
Console.WriteLine($"{data[0]}, {data[1]}, {data[2]}, {data[3]}, {data[4]}, {data[5]}");
}
}
}
我找到了这篇文章,并试图按照你的建议实施;它不起作用。我把它贴在我的密码里了。节点仍然为空,我也实现了它,在我的例子中,一切都按预期工作。将整个代码粘贴到answerMan中我不知道如何感谢您!终于完美地工作了!!!你知道任何关于使用c和html敏捷性的网页废弃的材料吗?不知道。有很多关于使用python之类的脚本语言的内容。顺便说一句,如果你发现我的答案正确,你可以将它标记为你问题的答案。