public BarchartParser()
{
// Initialize list
StockSymbols = new List<string>();
// Add items
ParseBarchart();
}
这是调用方法解析HTML
private async void ParseBarchart()
{
try
{
#region Get Html Document
// Get response from site
HttpClient http = new HttpClient();
var response = await http.GetByteArrayAsync(BARCHART_WEBSITE);
/* Break or W/e happens on this line ^^^ */
// Encode html response to UTF-8
string source = Encoding.GetEncoding(BARCHART_ENCODING)
.GetString(response, 0, response.Length - 1);
// Get html
HtmlDocument document = new HtmlDocument();
document.LoadHtml(source);
#endregion
#region Get Data From Table
// Get table containining stock info
HtmlNode table = document.DocumentNode.Descendants()
.Single<HtmlNode>
(
x => (x.Name == "table") &&
(x.Attributes["class"] != null) &&
(x.Attributes["class"].Value.Equals("datatable ajax")) &&
(x.Attributes["id"].Value.Equals("dt1"))
);
// Get 'tbody' element from table
HtmlNode tbody = table.Descendants("tbody").FirstOrDefault();
// Get all rows from the table
List<HtmlNode> allStocks = tbody.Descendants("tr").ToList();
// For each row, id is "td1_X" where X is the symbol of the stock
foreach (HtmlNode row in allStocks)
{
StockSymbols.Add(row.Attributes["id"].Value.ToString()
.Split(new char[] { '_' })[1]);
}
#endregion
}
catch
{
StockSymbols = new List<string>();
StockSymbols.Add("this didn't work");
}
}
而从一个简单的表格应用程序中的代码,使用这个C'tor:
BarchartParser barchartData;
public Form1()
{
InitializeComponent();
barchartData = new BarchartParser();
}
private void Form1_Load(object sender, EventArgs e)
{
if (barchartData.StockSymbols != null && barchartData.StockSymbols.Count > 0)
MessageBox.Show(barchartData.StockSymbols[0]);
else
MessageBox.Show("barchartData.StockSymbols is null or count == 0");
this.Close();
}
不完全确定这里发生了什么。它工作了一次,我调试,然后停止工作。
此代码是在C'tor期间调用的函数的一部分。当这个抛出或任何发生,
它只是继续到我在调试模式下设置的下一个断点...任何人都有什么线索
可能是这样的原因?
编辑:我知道这不是抛出,因为catch块中的代码不会发生。它只是对
移动只是一般,我按照本指南https://code.msdn.microsoft.com/Parsing-Html-using-C-721be358/sourcecode?fileId=122353&pathId=1834557721
代码如图不足以图个问题。最可能的问题是调用此代码,因为您无法在构造函数中“等待”......请提供相对完整的示例(方法的方法和调用者)以获取答案。 –
根据要求,基本上我写的所有代码到目前为止 –
正如预期的那样,您不是在等待结果 - 请参阅我的答案。 –