需求:我们有时候想要访问一个网址(A:http://xxx.com/data.php)来获取自己想要的东西,访问后由于我们没有登录,系统为我们重定向到另一个网址(B:http://xxx.com/login.php)
我们已知一个账号admin/password
用python完成认证过程并请求A网址:
# -*-coding:UTF-8 -*-
import urllib
import urllib2
import re
import sys
import cookielib
def auth():
headers = {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate, sdch',
'Accept-Language':'zh-CN,zh;q=0.8',
'Connection':'keep-alive',
'Host':'x.x.x.x',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36'
}
url_A = 'http://xxx.com/data.php'
url_B = 'http://xxx.com/login.php'
data = {
"username":"admin",
"password":"password"
}
post_data = urllib.urlencode(data)
cookieJar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
req = urllib2.Request(url_A,post_data,headers)
result = opener.open(req)
result = opener.open(url_A)
print result.read()
print 'done'
if __name__ == '__main__':
print 'begin:'
auth()