从网页中检索图像网址

时间:2012-05-20 15:46:28

标签: c# html windows-phone-7 exception-handling html-agility-pack

string imgurlhard = doc.DocumentNode.
    Element("html").
    Element("body").
    Elements("div").Single(el => el.Attributes["id"].Value == "main").
    Elements("div").Single(el => el.Attributes["id"].Value == "onlineIntegrator").
    Elements("div").Single(el => el.Attributes["id"].Value == "results").
    Element("img").Attributes["src"].Value; 

MessageBox.Show(imgurlhard);

以下是要检索的网页的网址:

http://integrals.wolfram.com/index.jsp?expr=sin(x)&random=false

任何人都可以告诉我我做错了什么因为我抓到了NullReferenceException

2 个答案:

答案 0 :(得分:1)

var image = doc.DocumentNode
    .Descendants("img")
    .Where(i => i.Attributes["class"] != null && i.Attributes["class"].Value == "traditionalForm")
    .Select(i => i.Attributes["src"].Value)
    .FirstOrDefault();

答案 1 :(得分:0)

我建议使用HTMLagility。

string image = Doc.DocumentNode.SelectSingleNode("//div[@id='traditionalForm']//img['src'][1]").Attributes["src"].Value;

修改

现在应该可以了。

相关问题