python-代码库 :requests 模拟登陆网站

requests 模拟登陆网站


当我们需要浏览登陆后的网站内容时,就需要模拟登陆网站,为了维持登陆状态,就需要用到session来维持整个会话,requests库中对应的requests.session()便可以帮我们完成这些。


代码:


#!/usr/bin/python
#-*-coding:UTF-8-*-

‘’‘
coding:gooyii
date:20170606
’‘’

import requests

login_url = "http://www.xxx.com/login"
data = {"username":"admin","password":"letmein"}

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2',
    'Connection': 'keep-alive',
    'Host': 'www.zhihu.com',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36',
    'Referer': 'http://www.xxx.com/',

#获取登陆状态下的session
def getSession(URL,DATA,HEADERS):
	_session = requests.session()
	_session.post(URL,data = DATA,headers = HEADERS,verify = False)
	return _session

#访问后面网页的时候就是带着session的登陆状态了
session = getSession(url,data,headers)
res = session.get(url,verify = False) 
print (res.text)



上一篇:Java实现单向双向链表原理分析


下一篇:Cocos2d-x3.2 文件读写