python 自动登录访问网站

  用程序自动登录某网站:

  1、首先在浏览器手动登录某网站

  2、从浏览器获取cookie

  3、在程序中把获取的cookie设置在程序中就可以自动登录

  下面list_cooke 可以通过google浏览器的EditThisCookie插件导出

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


def get_driver(proxy, headless=True):
    chrome_options = Options()
    if headless:
        chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])
    chrome_options.add_argument(
        'user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"')
    if proxy:
        chrome_options.add_argument('--proxy-server=' + proxy)
    driver = webdriver.Chrome(chrome_options=chrome_options)
    driver.set_page_load_timeout(60)
    driver.maximize_window()
    return driver


def logon_web():
    driver = get_driver('', False)
    try:
        url = 'https://www.baidu.com/'
        driver.get(url)
        driver.delete_all_cookies()
        list_cooke =[
{
    "Domain": ".baidu.com",
    "expirationDate": 1640169402,
    "hostOnly": False,
    "httpOnly": False,
    "name": "BA_HECTOR",
    "path": "/",
    "SameSite": "unspecified",
    "secure": False,
    "session": False,
    "storeId": "0",
    "value": "81a02lak212l8100r61gs5sda0q",
    "id": 1
},
{
    "Domain": ".baidu.com",
    "expirationDate": 1671701707.753021,
    "hostOnly": False,
    "httpOnly": False,
    "name": "BAIDUID",
    "path": "/",
    "SameSite": "unspecified",
    "secure": False,
    "session": False,
    "storeId": "0",
    "value": "295E4D533D77D7DDEF8FA7C4D846CCB4:FG=1",
    "id": 2
},
}
]
        for cook in list_cooke:
            driver.add_cookie(cook)
        driver.refresh()

    except Exception as ex:
        print(ex)
    driver.quit()

if __name__ == '__main__':
    logon_web()
    print(1)
View Code

 

posted on 2021-12-22 17:48  shaomine  阅读(894)  评论(0编辑  收藏  举报