我正在使用C#并使用HTMLAgilityPack从网页获取内容,我正在尝试解析数据并提取我需要的某些元素。
<tr height=20 onMouseOver="this.bgColor = '#C0C0C0'" onMouseOut="this.bgColor = 'whitesmoke'" bgcolor=whitesmoke>
<td>9</td>
<td align=left><a href="link to page" style="color:blue; text-decoration:none">PlayerFirstName Surname</a></td>
<td>Position</td>
<td width=30 align=right bgcolor=dcdcdc>3</td>
<td width=30 align=right>6</td>
<td width=30 align=right>4</td>
<td width=30 align=right>2</td>
<td width=30 align=right>0</td>
<td width=30 align=right>0</td>
</tr>
上面是我要从特定网页解析的HTML片段。 我只对这些标签的文字感兴趣。总共9个值。 值:9,播放器名称,位置以及其余六个标签中剩余的六个数字(3,6,4,2,0,0)。
不幸的是,我试图解决这个问题的方式并不像我想要的那样有效。这是我用来尝试将每个值分成单独变量的C#代码。
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(teamUrl);
foreach(HtmlNode node in doc.DocumentNode.Descendants("tr"))
{
string[] lines = node.InnerText.Split(new[] { "\r\n", "\r", "\n"}, StringSplitOptions.None).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
listOfPlayers.Add(new Player(lines[0], lines[1], lines[2], lines[3]....lines[8]));
}
** 上面的字符串数组“lines”输出以下的Count()为4.所以我调用将元素传递给listOfPlayers不起作用。
2
姓姓
中场/前进
121100
剩余的六个值连接在一起,我无法想出如何将它们分开。
它似乎应该是,而且可能是一项简单的任务,但我对HTML并不熟悉,只回到C#编程,所以任何帮助都会很棒。感谢。
编辑:
玩家对象 -
class Player
{
public int ShirtNumber { get; private set; }
public string Name { get; private set; }
public string Position { get; private set; }
public int GamesPlayed { get; private set; }
public int Points { get; private set; }
public int GoalsScored { get; private set; }
public int Assists { get; private set; }
public int YellowCards { get; private set; }
public int RedCards { get; private set; }
public Player(int shirtNumber, string name, string position,
int gamesPlayed, int points, int goalsScored, int assists, int yellowCards, int redCards)
{
ShirtNumber = shirtNumber;
Name = name;
Position = position;
GamesPlayed = gamesPlayed;
Points = points;
GoalsScored = goalsScored;
Assists = assists;
YellowCards = yellowCards;
RedCards = redCards;
}