python 用requests模块自动登录

用requests模块重新写了下。
需要启用requests的会话保持。要不然登录后,访问其他网页会断掉连接

-- coding: utf-8 --

import urllib2
import urllib
import cookielib
import re
import sys
reload(sys)
import requests
from bs4 import BeautifulSoup
sys.setdefaultencoding(“utf-8”)

设置cookie

cj = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

添加headers

opener.addheaders=[(“User-Agent”,”Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36”),]
urllib2.install_opener(opener)

登录网站

url = ‘http://www.xinxianwang.com/login/login.asp’

POST 数据

values = {
‘username’:’cqmyg12342322’,
‘password’:’cq123456’,
‘k’:’Fri Oct 23 2015 23:39:12 GMT+0800 (中国标准时间)40000’
}
post_header ={
“Referer”:”http://www.xinxianwang.com/login/“,
“User-Agent”:”Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36”,
“Accept-Encoding”:”gzip, deflate”,
“Accept-Language”:”zh-CN,zh;q=0.8”,
“Connection”:”keep-alive”,
“Content-Length”:”175”,
“Content-Type”:”application/x-www-form-urlencoded”
}

保存cookie

cj.save(‘H:\python_learn/wangyi.txt’)

设置会话话保持。用这个对象访问网站

s=requests.Session()
r = s.post(url, data=values,headers=post_header)
print r.content

mm = s.get(‘http://www.xinxianwang.com/my/‘,timeout=20).content
soup = BeautifulSoup(mm)
print soup.title

你可能感兴趣的:(python)