从url获取html源代码,css内联问题!

时间:2010-07-07 16:15:12

标签: c# asp.net

我有一个奇怪的问题:

我使用以下方法从url获取html源代码:

string html;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
   using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
   {
      html = reader.ReadToEnd();
      reader.Close();
   }
   response.Close();
}  

我请求的页面有这样的css内联:

<span class="VL" style="display:inline-block;height:20px;width:0px;"></span>

但是html var值只有:

<span class="VL" style="display:inline-block;"></span>

任何人都知道为什么?我已经测试了许多enconders并使用了WebRequest和WebClient,但也没有用。

2 个答案:

答案 0 :(得分:1)

您可能需要发送用户代理,以便该网站不认为您是机器人。当机器人请求时,有些网站不打扰CSS。此外,使用WebClient

可以简化远程HTML的读取
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4";
    string html = client.DownloadString(url);
}

答案 1 :(得分:0)

您是否通过浏览器开发工具查看源代码,方法是单击inspect元素?您是否有可能从浏览器中查看源代码,该浏览器通过JavaScript在客户端添加高度和宽度属性,并显示修改后的样式。