所以我偷懒写了一些东西,首先查询其他网站并加载所有相关的证券交易所符号,并尝试迭代这些符号并加载雅虎的服务器以获取最新的股票价格。由于某种原因,无论我尝试使用 HtmlAgilityPack 进行搜索,我似乎都无法获取任何相关信息。我不认为页面加载后运行的某些 JavaScript 存在问题(但我可能是错的)。
以下是一个通用例程,可以对其进行修改,以尝试从雅虎获取股票代码的百分比变化:
string symbol = "stock symbol"
string link = @"http://finance.yahoo.com/q?uhb=uh3_finance_vert&s=" + symbol;
string data = String.Empty;
try
{
// keep in this scope so wedget and doc deconstruct themselves
var webget = new HtmlWeb();
var doc = webget.Load(link);
string percGrn = doc.FindInnerHtml("//span[@id='yfs_pp0_" + symbol + "']//b[@class='yfi-price-change-up']");
string percRed = doc.FindInnerHtml("//span[@id='yfs_pp0_" + symbol + "']//b[@class='yfi-price-change-down']");
// create somthing we'll nuderstand later
if ((String.IsNullOrEmpty(percGrn) && String.IsNullOrEmpty(percRed)) ||
(!String.IsNullOrEmpty(percGrn) && !String.IsNullOrEmpty(percRed)))
throw new Exception();
// adding string to empty gives string
string perc = percGrn + percRed;
bool isNegative = String.IsNullOrEmpty(percGrn);
double percDouble;
if (double.TryParse(Regex.Match(perc, @"\d+([.])?(\d+)?").Value, out percDouble))
data = (isNegative ? 0 - percDouble : percDouble).ToString();
}
catch (Exception ex) { }
finally
{
// now we need to check what we have and load into the datgridView
if (!newData_d.ContainsKey(symbol)) newData_d.Add(symbol, data);
else MessageBox.Show("ERROR: Duplicate stock Symbols for: " + symbol);
}
这是 FindInnerHtml 的扩展方法:
// this is for the html agility class
public static string FindInnerHtml( this HtmlAgilityPack.HtmlDocument _doc, string _options)
{
var node = _doc.DocumentNode.SelectSingleNode(_options);
return (node != null ? node.InnerText.ToString() : String.Empty);
}
任何有关找回东西的帮助将不胜感激,谢谢!
///////////////////////////////////////////////////////////////////////// 编辑: ////////////////////////////////////////
我突出显示了跨度 id,然后查看第 239 行,看看我在哪里看到了“yfi-price-change-up”引用:
最佳答案
以下XPath成功找到目标<span>
其中包含增加(或减少)的百分比:
var doc = new HtmlWeb().Load("http://finance.yahoo.com/q?uhb=uh3_finance_vert&s=msft");
var xpath = "//span[contains(@class,'time_rtq_content')]/span[2]";
var span = doc.DocumentNode.SelectSingleNode(xpath);
Console.WriteLine(span.InnerText);
输出:
(0.60%)
关于javascript - c# HtmlAgilityPack 和 Yahoo 的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37357439/