'''訪問登錄頁面請求URL:https://github.com/login請求方式:GET請求頭:COOKIESUser-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.362.解析並提取token字符串#正則<input type="hidden" name="authenticity_token" value="(.*?)" />#字符串uj+bTJF3L3lfBg4YfijNJ0VPUqR0UWCmD0CPDGJY8jjT4GpzV6AYNx5VRFWzCxnpOdk3n62J9/qzeXbQEwXTCw=='''import requestsimport relogin_url = 'https://github.com/login'# login頁面的請求頭信息login_header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}login_res = requests.get(url=login_url, headers=login_header)# print(login_res.text)# 解析提取token字符串authenticity_token = re.findall( '<input type="hidden" name="authenticity_token" value="(.*?)" />', login_res.text, re.S)[0]print(authenticity_token)login_cookies = login_res.cookies.get_dict()# 2.開始登錄github'''post請求自動登錄github: 請求URL:https://github.com/session 請求方式:POST 請求頭: Cookie User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36 請求體: commit: Sign in utf8: ✓ authenticity_token: 0cfliMWH1jCxz8hDcBHBRSmN7sg6/VYvEAwnCdXUErfZPIfu52UGnh/S8mYguH1GAyGmBTuilMTXB6tL9Zsgzg== login: ***** password: ****** webauthn-support: supported '''#session登錄urlsession_url = 'https://github.com/session'#請求頭信息session_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}#請求體信息form_data = { "commit": "Sign in", "utf8": "✓","authenticity_token": authenticity_token,"login": "****** ","password":"******","webauthn - support": "supported"}session_res = requests.post( url=session_url, headers=session_headers, cookies=login_cookies, data=form_data)with open('github.html','w',encoding='utf-8')as f: f.write(session_res.text)