我已经尝试了很长时间,但这是我的情况;
我 friend 的 Web 应用程序使用非常简单的 HTML 运行一个网站来生成图表数据。我想从该页面上的表中获取某些值,因为他需要将此信息存储到数据库中。
所以这是HTML表格的一部分;
...
<tr>
<td width=30 align=center bgcolor=#006699 class=W><font color=white>1</font></td>
<td width=50 bgcolor=#FFFFFF align=center>7387</td>
<td width=30 height=25 align=center bgcolor=#006699 class=W><font color=white>2</font></td>
<td width=50 bgcolor=#FFFFFF align=center>2881</td>
<td width=30 height=25 align=center bgcolor=#006699 class=W><font color=white>3</font></td>
<td width=50 bgcolor=#FFFFFF align=center>8782</td>
<td width=30 height=25 align=center bgcolor=#006699 class=W><font color=white>4</font></td>
<td width=50 bgcolor=#FFFFFF align=center>5297</td>
<td width=30 height=25 align=center bgcolor=#006699 class=W><font color=white>5</font></td>
<td width=50 bgcolor=#FFFFFF align=center>749</td>
</tr>
<tr>
<td align=center bgcolor=#006699 class=W><font color=white>6</font></td>
<td width=50 bgcolor=#FFFFFF align=center>3136</td>
<td height=25 align=center bgcolor=#006699 class=W><font color=white>7</font></td>
<td width=50 bgcolor=#FFFFFF align=center>8768</td>
<td height=25 align=center bgcolor=#006699 class=W><font color=white>8</font></td>
<td width=50 bgcolor=#FFFFFF align=center>9548</td>
<td height=25 align=center bgcolor=#006699 class=W><font color=white>9</font></td>
<td width=50 bgcolor=#FFFFFF align=center>6565</td>
<td height=25 align=center bgcolor=#006699 class=W><font color=white>10</font></td>
<td width=50 bgcolor=#FFFFFF align=center>142</td>
</tr>
...
我想达到的是;
- 我得到两个数字 - 例如 1 和 8。
- 我的应用程序检查页面的 HTML 并选择包含数字的两个
td(如上所示)。 - 然后,我必须获取 NEXT
td的值。
此输出将是 1=7387 和 8=9548。 在尝试找到包含给定数字的两个 td 后,我很快就卡住了。
到目前为止我的 C# 代码;
using (WebClient webClient = new WebClient())
{
string completeHTMLCode = webClient.DownloadString("someUrl.php?getChartData=" + chartId);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(completeHTMLCode);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//td[@...]"))
{
}
}
我是不是在尝试一些不可能的事情?
请您参考如下方法:
我制作了一个快速的 CsQuery 示例,说明如何完成此操作。
string file = File.ReadAllText("a.html"); // gets the html
CQ dom = file; // initializes csquery
CQ td = dom["td"]; // get all td files
td.Each((i,e) => { // go through each
if (e.FirstChild != null) // if element has child (font)
{
if (e.FirstChild.NodeType != NodeType.TEXT_NODE) // ignore text node
{
if (e.FirstChild.InnerText == "1") // if number is 1
{
Console.WriteLine(e.NextElementSibling.InnerText); // output the text
}
if (e.FirstChild.InnerText == "8") // etc etc
{
Console.WriteLine(e.NextElementSibling.InnerText);
}
}
}
});
Console.ReadKey();
