【问题标题】:How to Enable Javascript When Making an HttpWebRequest发出 HttpWebRequest 时如何启用 Javascript
【发布时间】:2009-12-30 20:38:54
【问题描述】:

我需要调用一个有 javascript 的网页。在页面底部我有以下内容:

  <noscript>
    <p>Javascript is not supported or enabled.</p>
  </noscript>

当我像这样发出 HttpWebRequest 请求时,很明显页面上的 javascript 没有执行。

Dim req As System.Net.HttpWebRequest = DirectCast(System.Net.WebRequest.Create(New Uri(url)), System.Net.HttpWebRequest)
' Add the current authentication cookie to the request 
Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies(FormsAuthentication.FormsCookieName)
Dim authenticationCookie As New System.Net.Cookie(FormsAuthentication.FormsCookieName, cookie.Value, cookie.Path, HttpContext.Current.Request.Url.Authority)

req.CookieContainer = New System.Net.CookieContainer()
req.CookieContainer.Add(authenticationCookie)
req.MediaType = "PRINT"
req.Method = "GET"
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"

Dim res As System.Net.WebResponse = req.GetResponse()

我能做什么?如果 javascript 没有运行,响应对我没有用。我想将输出转换为 PDF。我想我需要一种方法来执行响应中包含的 javascript,但要在浏览器之外执行。

谢谢。

【问题讨论】:

    标签: asp.net javascript httpwebrequest


    【解决方案1】:

    您要转换什么输出?您只能抓取静态 HTML,不能抓取 JavaScript 修改的 DOM。

    请记住,HttpWebRequest 不解释 JavaScript。

    【讨论】:

      【解决方案2】:
      1. 像以前一样使用 HttpWebRequest
      2. 在 GetResponse 和 GetResponseStream 之后,将流内容保存为临时文件(例如,使用 Path.GetTempFilename() 方法中的文件名)
      3. 将其加载到 The WebBrowser class。
      4. 让页面自行执行一段时间。
      5. 浏览 Web 浏览器实例的 representation of the DOM 即可获得所需内容。

      希望这会有所帮助。

      【讨论】:

        【解决方案3】:

        Javascript 在用户代理(客户端)上执行。您正在为请求提供错误的用户代理字符串。您“假装”的用户代理具有 Javascript 实现。当然,HttpWebRequest 没有。

        【讨论】:

          【解决方案4】:

          我想我需要一种方法来执行 包含在 响应,但这样做之外 浏览器。

          然后您需要编写自己的 jasvascript 解释器。

          我能想到的唯一选择是使用任何 Web 浏览器引擎(如 webkit、gecko 等)在服务器端为您呈现页面或搜索在线服务(如 browsershots)将为您呈现页面.

          【讨论】:

            【解决方案5】:

            修复页面,使其不依赖于 JavaScript。 Build on things that work.

            【讨论】:

            • 也许不是他的页面。我也有同样的问题。我不拥有或控制要连接的网络服务器,但我需要执行 javascript,因为某些内容(cmets)是由 js 加载的...
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-02-28
            • 2014-04-12
            • 2011-11-15
            相关资源
            最近更新 更多