模擬用戶登錄(獲取cookie/實例化session)


第一種方法:通過本地瀏覽器保存的cookie進行登陸

url1 = 'https://passport.cnblogs.com/user/signin?ReturnUrl=https%3A%2F%2Fwww.cnblogs.com%2F'

url2 = 'https://www.cnblogs.com/Dark-fire-liehuo/'

# 1、通過本地瀏覽器保存的cookie進行登陸
# 注意這個要請求登陸之后的頁面,才能證明登陸成功
# 第一種獲取cookie用戶信息
#登錄時請求的url必須是用戶登錄后的url
headers = {
    "cookie": "_ga=GA1.2.1965586441.1532740971; __gads=ID=09a445c8f1ff60fb:T=1535718026:S=ALNI_MZMRNk-7R8fVRqMF9bIBNiWG9Hx0w; _gid=GA1.2.1535339514.1542420337; .CNBlogsCookie=21B80E72A85B82C361A5CEEA392261243AA7C2EECA0CADE6C84FF17AC84BF1BCC32BC6A406276FE9542C4772C1324691CCF3F977CE0DDE400B061237BDF01380BDCCB6C647A295404B4FB0903B2288E6E4CA33C2; .Cnblogs.AspNetCore.Cookies=CfDJ8J0rgDI0eRtJkfTEZKR_e82R2q3HJVLaq66dCusFQqJZJDxM4KAk3iTzpmj6GoICVZF79Oz5N6qZVAPvmepKbQj-dYwondwMxBYWS3Ict8yh3mFXPrITE9fM5ueV_6wC0LWVUnEZHe4p8mKDMwuyjJiuoWKSzWoaq3TjBLgpmGbkU8acaJhfzv1jHkrSaeU7oe69dMbpOI6jTXaEUyEBtj5iFyqNLqFP_4zsKCR33hLZKfAb5U_eAlOBBbj52QYe7f5VxktpLTdjZs1nqTC2LcwNO2EERcef002F8pb9Maen",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36",
}
response = requests.get(url2, headers=headers)
print(response.content.decode())

第二種方法:實例化一個session對象,通過session對象發送post請求

# 2、實例化一個session對象,通過session對象發送post請求

url3 = "http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=2018106935111"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"
}
data = {
    "email":18520877258,
    "password":"sxt123456"
}

sess = requests.session()
response = sess.post(url3,headers=headers,data=data)

content = response.content.decode()

print(content)
# 設置成功后會返回一個cookie值
print(sess.cookies)

# 將cookiejar類型的轉成字典形式的方法
dic_cookies = requests.utils.dict_from_cookiejar(sess.cookies)
print(dic_cookies)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM