Search code examples
pythonpython-3.xpython-2.7urlliburllib2

Using python to login to a website that use cookies


Im trying to log on into this website (https://phishtank.org/login.php) to use it with python, but the site use cookies. I tried this:

import urllib

cookies = {
    'PHPSESSID': '3hdp8jeu933e8t4hvh240i8rp840p06j',
}

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3',
    'Referer': 'https://phishtank.org/login_required.php',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'same-origin',
    'Sec-Fetch-User': '?1',
    'Cache-Control': 'max-age=0',
    'TE': 'trailers',
}

response = requests.get('https://phishtank.org/add_web_phish.php', headers=headers, cookies=cookies)

print(response.text)

It works, but after a few minutes the cookie just expires. What can I do to avoid this limitation? Maybe somethin that request new cookies for me and use it.


Solution

  • Use request sessions instead. It persists cookies for you

    import requests
    session = requests.Session()
    session.headers.update(headers)
    session.cookies.update(cookies)
    
    session.get(<url>)