3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using HtmlAgilityPack;

namespace sss
{
    public class Downloader
    {
        WebClient client = new WebClient();

        public HtmlDocument FindMovie(string Title)
        { 
            //This will be implemented later on, it will search movie.
        }

        public HtmlDocument FindKnownMovie(string ID)
        {
            HtmlDocument Page = (HtmlDocument)client.DownloadString(String.Format("http://www.imdb.com/title/{0}/", ID));
        }
    }
}

如何将下载的字符串转换为有效的 HtmlDocument,以便使用 HTMLAgilityPack 对其进行解析?

4

4 回答 4

6

这应该适用于 v1.4:

HtmlWeb hw = new HtmlWeb();
HtmlDocument doc = hw.Load(string.Format("http://www.imdb.com/title/{0}/", ID));

或者

string html = client.DownloadString(String.Format("http://www.imdb.com/title/{0}/", ID));
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
于 2010-06-11T14:46:21.223 回答
5

试试这个(基于这个相当古老的文档):

string url = String.Format("http://www.imdb.com/title/{0}/", ID);
string content = client.DownloadString(url);
HtmlDocument page = new HtmlDocument();
page.LoadHtml(content);

基本上,强制转换很少是在两种类型之间转换的正确方法——尤其是在进行解析之类的事情时。

于 2010-06-11T14:45:36.887 回答
1

以下代码行将HtmlDocument使用您的内容创建一个:

// First create a blank document
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
// Then load it with the content from the webpage you are trying to parse
doc.Load(new StreamReader(WebRequest.Create("yourURL").GetResponse()
                                 .GetResponseStream()));
于 2010-06-11T14:46:26.120 回答
0

也许您可以在文件系统中创建一个新文件 (.html),然后使用流编写器将字符串写入 html 文件。然后将该文件传递给解析器

于 2010-06-11T14:46:10.647 回答