【问题标题】:How can i get the html of the page? [duplicate]我怎样才能得到页面的html? [复制]
【发布时间】:2013-12-30 09:45:38
【问题描述】:

这是我用来执行网络请求的代码。除了 URL 中的 cmets 部分之外,我正在获取所有 HTML。

HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(
  "http://u-handbag.typepad.com/uhandblog/2013/11/choosing-bag-fabrics.html#comment-6a00d8341c574653ef019b022fc96f970d"
);
StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream());
htl = reader.ReadToEnd();

谁能解释一下原因?

【问题讨论】:

  • 说实话,我真的不知道,但javascript不会修改输出。也许这就是为什么你有不同的数据。

标签: c#


【解决方案1】:

从网站页面获取 HTML 代码。你可以使用这样的代码。

string urlAddress = "http://u-handbag.typepad.com/uhandblog/2013/11/choosing-bag-fabrics.html#comment-6a00d8341c574653ef019b022fc96f970d";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
  Stream receiveStream = response.GetResponseStream();
  StreamReader readStream = null;
  if (response.CharacterSet == null)
    readStream = new StreamReader(receiveStream);
  else
    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
  string data = readStream.ReadToEnd();
  response.Close();
  readStream.Close();
}

或更好地使用WebClient

        using System.Net;
        using (WebClient client = new WebClient())
        {
            string htmlCode = client.DownloadString("http://u-handbag.typepad.com/uhandblog/2013/11/choosing-bag-fabrics.html#comment-6a00d8341c574653ef019b022fc96f970d");
        }

【讨论】:

  • 亲爱的我应用此代码但未能获得(cmets 部分(在上面的 url 中))............
  • 在我的机器上它可以工作。你得到什么错误
  • @F.R.I.E.N.D.S.谢谢x
  • 我无法在 url 中获取 html 的 cmets 部分..请帮助我..?
【解决方案2】:

使用这段代码。变量result应该有html代码。

 System.Net.WebClient webClient = new System.Net.WebClient();
 string result = webClient.DownloadString(URL);

【讨论】:

  • 我这样做但失败了......
  • 我尝试了我发布的代码。它在我的机器上工作。我得到了一切,包括 cmets 部分。确保您的 URL 确实指向某些东西。请检查您的网址。
  • 亲爱的,每件事都是正确的ajax/jquery 请求???
  • 我不确定我是否遇到了您的问题。无论如何,我检查了 URL,并且 cmets 部分有指向另一个 URL 的链接,这意味着它确实使用 Ajax 来加载 cmets。如果您想获取 cmets 的 html 源代码,那么操作原始 URL(例如搜索评论 URL 并获取源代码)可能是一个好主意。实际上我以前做过这样的事情,所以我知道它有效。我只是不确定这是否是你想要的。
  • 是的,这正是我的问题如何解决?
猜你喜欢
  • 2019-06-21
  • 2012-10-02
  • 2018-02-22
  • 2020-12-05
  • 1970-01-01
  • 2017-12-18
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多