¿Cómo obtener las cookies del sitio web activo en una instancia del control WebBrowser?
Esta idea se me ocurrió por la necesidad de loguearme de forma interactiva (me refiero, manualmente mediante un WebBrowser) a un sitio web que tiene captcha y una pregunta aleatoria de seguridad... por lo cual iba a ser costoso o inviable automatizar la obtención de la cookie de la sesión mediante solicitudes POST en background.
Este código no tiene nada de especial, simplemente es una alternativa de uso para en lugar de utilizar la propiedad WebBrowser.Document.Cookie, la cual devuelve un String, con este código podemos obtener directamente una instancia de la clase CookieContainer o CookieCollection.
Este es el código:
Ejemplo de uso:
Esta idea se me ocurrió por la necesidad de loguearme de forma interactiva (me refiero, manualmente mediante un WebBrowser) a un sitio web que tiene captcha y una pregunta aleatoria de seguridad... por lo cual iba a ser costoso o inviable automatizar la obtención de la cookie de la sesión mediante solicitudes POST en background.
Este código no tiene nada de especial, simplemente es una alternativa de uso para en lugar de utilizar la propiedad WebBrowser.Document.Cookie, la cual devuelve un String, con este código podemos obtener directamente una instancia de la clase CookieContainer o CookieCollection.
Este es el código:
Código (vbnet) [Seleccionar]
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains custom extension methods to use with <see cref="WebBrowser"/> control.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
<HideModuleName>
Public Module WebBrowserExtensions
#Region " Public Extension Methods "
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets a <see cref="CookieContainer"/> containing the stored cookies for the active website
''' in the source <see cref="WebBrowser"/>.
''' (that is, the active opened document in the <see cref="WebBrowser.Document"/> property).
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <example> This is a code example.
''' <code>
''' Public Class Form1
'''
''' Private uri As New Uri("https://foro.elhacker.net/")
'''
''' Private Sub Form1_Shown(sender As Object, e As System.EventArgs) Handles MyBase.Shown
''' Me.WebBrowser1.ScriptErrorsSuppressed = True
''' Me.WebBrowser1.Navigate(uri)
''' End Sub
'''
''' Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
'''
''' Dim wb As WebBrowser = DirectCast(sender, WebBrowser)
''' If Not (wb.ReadyState = WebBrowserReadyState.Complete) OrElse Not (e.Url = Me.uri) Then
''' Exit Sub
''' End If
'''
''' Dim cookies As CookieContainer = GetCookieContainer(wb)
''' For Each cookie As Cookie In cookies.GetCookies(Me.uri)
''' Console.WriteLine(cookie.ToString())
''' Next cookie
'''
''' End Sub
'''
''' End Class
''' </code>
''' </example>
''' ----------------------------------------------------------------------------------------------------
''' <param name="wb">
''' The source <see cref="WebBrowser"/>.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The resulting <see cref="CookieContainer"/>.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
<Extension>
<EditorBrowsable(EditorBrowsableState.Always)>
Public Function GetCookieContainer(ByVal wb As WebBrowser) As CookieContainer
Dim uri As Uri = wb.Url
Dim cookieContainer As New CookieContainer()
Dim cookies As String() = wb.Document.Cookie.Split({";"c}, StringSplitOptions.None)
For Each cookie As String In cookies
Dim name As String = cookie.Substring(0, cookie.IndexOf("="c)).TrimStart(" "c)
Dim value As String = cookie.Substring(cookie.IndexOf("="c) + 1)
cookieContainer.Add(uri, New Cookie(name, value, "/", uri.Host))
Next cookie
Return cookieContainer
End Function
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Gets a <see cref="CookieCollection"/> containing the stored cookies for the active website
''' in the source <see cref="WebBrowser"/>.
''' (that is, the active opened document in the <see cref="WebBrowser.Document"/> property).
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <example> This is a code example.
''' <code>
''' Public Class Form1
'''
''' Private uri As New Uri("https://foro.elhacker.net/")
'''
''' Private Sub Form1_Shown(sender As Object, e As System.EventArgs) Handles MyBase.Shown
''' Me.WebBrowser1.ScriptErrorsSuppressed = True
''' Me.WebBrowser1.Navigate(uri)
''' End Sub
'''
''' Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
'''
''' Dim wb As WebBrowser = DirectCast(sender, WebBrowser)
'''
''' If Not (wb.ReadyState = WebBrowserReadyState.Complete) OrElse Not (e.Url = Me.uri) Then
''' Exit Sub
''' End If
'''
''' Dim cookies As CookieCollection = GetCookieCollection(wb)
''' For Each cookie As Cookie In cookies
''' Console.WriteLine(cookie.ToString())
''' Next cookie
'''
''' End Sub
'''
''' End Class
''' </code>
''' </example>
''' ----------------------------------------------------------------------------------------------------
''' <param name="wb">
''' The source <see cref="WebBrowser"/>.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The resulting <see cref="CookieCollection"/>.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
<Extension>
<EditorBrowsable(EditorBrowsableState.Always)>
Public Function GetCookieCollection(ByVal wb As WebBrowser) As CookieCollection
Dim uri As Uri = wb.Url
Return Cookies.GetCookieContainer(wb).GetCookies(uri)
End Function
#End Region
End Module
Ejemplo de uso:
Código (vbnet) [Seleccionar]
Imports WebBrowserExtensions
Public Class Form1
Private uri As New Uri("https://www.domain.com/")
Private Sub Form1_Shown(sender As Object, e As System.EventArgs) Handles MyBase.Shown
Me.WebBrowser1.ScriptErrorsSuppressed = True
Me.WebBrowser1.Navigate(uri)
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
Dim wb As WebBrowser = DirectCast(sender, WebBrowser)
If Not (wb.ReadyState = WebBrowserReadyState.Complete) OrElse Not (e.Url = Me.uri) Then
Exit Sub
End If
Dim cookies As CookieContainer = wb.GetCookieContainer()
For Each cookie As Cookie In cookies.GetCookies(Me.uri)
Console.WriteLine(cookie.ToString())
Next cookie
End Sub
End Class