轉載自:http://www.cnblogs.com/meitian/p/4607737.html
在做登錄的post請求時,需要記住cookie,否則不能訪問登錄后的頁面。
下面是登錄的代碼:
#coding:utf-8
import urllib
import http.cookiejar
url = "http://c.highpin.cn/Users/CLogin"
postdata =urllib.parse.urlencode({
"Logon_Password":"sunmin",
"Logon_PostCode":"fghc",
"Logon_RememberMe":"false",
"Logon_UserEmail":"sun121@qq.com"
}).encode('utf-8')
header = {
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Encoding":"utf-8",
"Accept-Language":"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3",
"Connection":"keep-alive",
"Host":"c.highpin.cn",
"Referer":"http://c.highpin.cn/",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0"
}
req = urllib.request.Request(url,postdata,header)
##print(urllib.request.urlopen(req).read().decode('utf-8'))
#自動記住cookie
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open(req)
print(r.read().decode('utf-8'))
以前用的是python2.7,但是python3開始很多包的位置和以前不一樣了,就對這里用到的說明一下:
urllib2合並到了urllib下,urlopen使用時包的位置為urllib.request.urlopen,urlencode使用包位置為urllib.parse.urlencode
cookielib變更為了http.cookiejar
說明:帶cookie的打印出來必須用opener.open(req).read().decode('utf-8')來發送的請求才會帶上cookie,如果用urllib.request.urlopen()是不帶cookie的
import urllib
url = "http://h.highpin.cn/ManageJob/PubJobCompany?Length=9"
postdata=urllib.parse.urlencode({
"JobName":"測試工程師",
"YearlySalaryMin":"11",
"YearlySalaryMax":"12",
"X-Requested-With":"XMLHttpRequest",
"WorkExperienceMin":"-1",
"WorkExperienceMax":"-1",
"TabId":"0",
"SubordinateCount":"0",
"SaveType":"1",
"ReportObject":"測試人",
"RecruitCount":"1",
"QualifiCation":"信息描述",
"ProfessionalName":"",
"nowCurrentPageIndex":"0",
"Memo":"限500字",
"MasteryDegree":"1",
"MajorID":"-1",
"LanguageType":"-1",
"JobTypeID":"1050000,4000000,160000",
"JobTagCount":"8",
"JobStatus":"1",
"JobDescription":"職位描述",
"JobAllTagStr":"五險一金",
"IsViewHighEndUser":"false",
"IsFull":"true",
"FullTime":"false",
"DepName":"測試",
"Degree":"-1",
"CompanyID":"2234",
"CloseDate":"2016-01-12",
"AreaID":"530",
"AgeMin":"-1",
"AgeMax":"-1"
}).encode('utf-8')
header={
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Encoding":"utf-8",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
"Host":"h.highpin.cn",
"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
"Referer":"http://h.highpin.cn/ManageJob/PubNewJob",
"Cookie":"XXXXX",
"Connection":"keep-alive"
}
req = urllib.request.Request(url,postdata,header)
r=urllib.request.urlopen(req)
print(r.read().decode('utf-8'))
Python3和Python2的變更,可以參考文章:http://blog.csdn.net/samxx8/article/details/21535901