Jump to content

How to get cookies and download a file with cookies?


Recommended Posts

How to grab cookies from a website url?

And how to download a file that needs cookies?

Here is a working python script but I really prefer AutoIt and I have no Python skill:

import os
import tempfile
import requests

def from_url(url, cookies=None):

    response = requests.get(url=url, cookies=cookies, allow_redirects=True, stream=True)
    filepath = tempfile.NamedTemporaryFile().name

    with open(filepath, 'wb') as f:
        for chunk in response.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
                f.flush()

    return filepath


def from_majorgeek(root):

    # Start a new requests session.
    session = requests.Session()

    # Get the root page cookies.
    response = session.get(root)
    cookies = session.cookies

    # Download the file.
    filepath = from_url('http://www.majorgeeks.com/index.php?ct=files&action=download&', cookies)

    # Return the downloaded file path.
    return filepath


if __name__ == '__main__':
    f = from_majorgeek('http://www.majorgeeks.com/mg/getmirror/chromium,1.html')
    print(f)

Thanks in advance for your help!

Edited by foozoor
Link to comment
Share on other sites

What kind of file you want to download ?
From where you get this Python code snippet ?

Edited by mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

17 minutes ago, mLipok said:

What kind of file you want to download ?
From where you get this Python code snippet ?

Sorry I forgot some piece of code in the first post. I fixed it now.

I want to download files from MajorGeek, from this kind of url:
http://www.majorgeeks.com/mg/getmirror/multi_commander,1.html

The python script grabs cookies from: http://www.majorgeeks.com/mg/getmirror/chromium,1.html

And download the file from http://www.majorgeeks.com/index.php?ct=files&action=download& by injecting the cookies.

I have got this script from multiple forums and stackoverflow.

Edited by foozoor
Link to comment
Share on other sites

Hello. You need to grab your cookie after login. then use/send it in your next request.

 

Saludos

Link to comment
Share on other sites

10 minutes ago, Danyfirex said:

Hello. You need to grab your cookie after login. then use/send it in your next request.

What do you mean by login?

I can't find a proper way to grab cookies and send/inject them to download the file with AutoIt. :(

Link to comment
Share on other sites

Link to comment
Share on other sites

You can get download links this way. Then just use InetGet or InetRead to download the files.

 

#include <InetConstants.au3>
#include <Array.au3>
#include <String.au3>
Global Const $sBaseURL = "http://www.majorgeeks.com/"


;~ AdsFix 3_11.08.2016.1 Read more at: https://tr.im/1XUul
Local $sURLProgramToDownload = "http://www.majorgeeks.com/files/details/adsfix.html"
Local $sData = BinaryToString(InetRead($sURLProgramToDownload, $INET_FORCERELOAD))



Local $aDownLoadsURLs = _StringBetween($sData, "images/arrowd.gif", '"><strong>')

If IsArray($aDownLoadsURLs) Then
    Local $iPos = 0
    For $i = 0 To UBound($aDownLoadsURLs) - 1
        $iPos = StringInStr($aDownLoadsURLs[$i], 'href="') + 6 ;get Correct URL Path
        $aDownLoadsURLs[$i] = $sBaseURL & StringMid($aDownLoadsURLs[$i], $iPos)
    Next
;~  _ArrayDisplay($aDownLoadsURLs)
    Local $aDownloadLinks[UBound($aDownLoadsURLs)]

    Local $sHotLinkData = ""
    Local $aDebugLink = 0
    ;Get Valid HotLinks for download using InetGet
    For $i = 0 To UBound($aDownloadLinks) - 1
        $sHotLinkData = BinaryToString(InetRead($aDownLoadsURLs[$i], $INET_FORCERELOAD))
        $aDebugLink = _StringBetween($sHotLinkData, 'Debug:', '-->')
        If IsArray($aDebugLink) Then
            $aDownloadLinks[$i] = StringStripWS($aDebugLink[0], $STR_STRIPALL)
        EndIf
    Next

    _ArrayDisplay($aDownloadLinks)
    ;use InetGet to download 

EndIf

 

Edit: if you want to download using the url you show like  http://www.majorgeeks.com/mg/getmirror/multi_commander,1.html

you just need to do one step. check code in ;Get Valid HotLinks for download using InetGet

 

Saludos

Edited by Danyfirex
Link to comment
Share on other sites

This small code is very raw (no details/error checking etc) but it works for me

$oHTTP = ObjCreate("WinHttp.WinHttpRequest.5.1")
; get cookie
$oHTTP.Open("GET", "http://www.majorgeeks.com/mg/getmirror/symenu,1.html")
$oHTTP.Send()
$rh = $oHTTP.GetAllResponseHeaders()
$cookie = StringRegExpReplace($rh, '(?s).*SESSID=(\w+).*', "$1")
   ; msgbox(0,"", $cookie)
; then download
$oHTTP.Open("GET", "http://www.majorgeeks.com/index.php?ct=files&action=download&")
$oHTTP.setRequestHeader("Cookie", $cookie)
$oHTTP.Send()
$data = $oHTTP.ResponseBody()
FileWrite("symenu.zip", $data)

 

Link to comment
Share on other sites

11 hours ago, Danyfirex said:

You can get download links this way. Then just use InetGet or InetRead to download the files.

 

#include <InetConstants.au3>
#include <Array.au3>
#include <String.au3>
Global Const $sBaseURL = "http://www.majorgeeks.com/"


;~ AdsFix 3_11.08.2016.1 Read more at: https://tr.im/1XUul
Local $sURLProgramToDownload = "http://www.majorgeeks.com/files/details/adsfix.html"
Local $sData = BinaryToString(InetRead($sURLProgramToDownload, $INET_FORCERELOAD))



Local $aDownLoadsURLs = _StringBetween($sData, "images/arrowd.gif", '"><strong>')

If IsArray($aDownLoadsURLs) Then
    Local $iPos = 0
    For $i = 0 To UBound($aDownLoadsURLs) - 1
        $iPos = StringInStr($aDownLoadsURLs[$i], 'href="') + 6 ;get Correct URL Path
        $aDownLoadsURLs[$i] = $sBaseURL & StringMid($aDownLoadsURLs[$i], $iPos)
    Next
;~  _ArrayDisplay($aDownLoadsURLs)
    Local $aDownloadLinks[UBound($aDownLoadsURLs)]

    Local $sHotLinkData = ""
    Local $aDebugLink = 0
    ;Get Valid HotLinks for download using InetGet
    For $i = 0 To UBound($aDownloadLinks) - 1
        $sHotLinkData = BinaryToString(InetRead($aDownLoadsURLs[$i], $INET_FORCERELOAD))
        $aDebugLink = _StringBetween($sHotLinkData, 'Debug:', '-->')
        If IsArray($aDebugLink) Then
            $aDownloadLinks[$i] = StringStripWS($aDebugLink[0], $STR_STRIPALL)
        EndIf
    Next

    _ArrayDisplay($aDownloadLinks)
    ;use InetGet to download 

EndIf

 

Edit: if you want to download using the url you show like  http://www.majorgeeks.com/mg/getmirror/multi_commander,1.html

you just need to do one step. check code in ;Get Valid HotLinks for download using InetGet

 

Saludos

Thank you for this approach.

5 hours ago, mikell said:

This small code is very raw (no details/error checking etc) but it works for me

$oHTTP = ObjCreate("WinHttp.WinHttpRequest.5.1")
; get cookie
$oHTTP.Open("GET", "http://www.majorgeeks.com/mg/getmirror/symenu,1.html")
$oHTTP.Send()
$rh = $oHTTP.GetAllResponseHeaders()
$cookie = StringRegExpReplace($rh, '(?s).*SESSID=(\w+).*', "$1")
   ; msgbox(0,"", $cookie)
; then download
$oHTTP.Open("GET", "http://www.majorgeeks.com/index.php?ct=files&action=download&")
$oHTTP.setRequestHeader("Cookie", $cookie)
$oHTTP.Send()
$data = $oHTTP.ResponseBody()
FileWrite("symenu.zip", $data)

 

Thank you, it corresponds perfectly to my problem and you solved it!

What are these errors and details to check?
Is there a way to improve the script?

Is there a way to retrieve the filename automatically or at least its extension while downloading?

Edited by foozoor
Link to comment
Share on other sites

  • 9 months later...

I would like to know on what kind of programming coding is.

PowerShell?

Do you have any suggestions?
Thanks, to everyone very much for any suggestions :>

 

 

On 8/12/2016 at 3:37 PM, mikell said:

This small code is very raw (no details/error checking etc) but it works for me

$oHTTP = ObjCreate("WinHttp.WinHttpRequest.5.1")
; get cookie
$oHTTP.Open("GET", "http://www.majorgeeks.com/mg/getmirror/symenu,1.html")
$oHTTP.Send()
$rh = $oHTTP.GetAllResponseHeaders()
$cookie = StringRegExpReplace($rh, '(?s).*SESSID=(\w+).*', "$1")
   ; msgbox(0,"", $cookie)
; then download
$oHTTP.Open("GET", "http://www.majorgeeks.com/index.php?ct=files&action=download&")
$oHTTP.setRequestHeader("Cookie", $cookie)
$oHTTP.Send()
$data = $oHTTP.ResponseBody()
FileWrite("symenu.zip", $data)

 

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...