from urllib.request import Request,build_opener,HTTPCookieProcessor
from urllib.parse import urlencode #转换用的
from fake_useragent import UserAgent
from http.cookiejar import MozillaCookieJar#保存cookie得文件需要引进的模块
def get_cookie():
login_url='http://learn.open.com.cn/Account/Login'#登录网站的url
from_data={
"user": "jxt17703612482",
"password": "JXTjxt00"
}
headers={"UserAgent":UserAgent().random}
rep=Request(login_url, headers=headers, data=urlencode(from_data).encode())
cookie_jar=MozillaCookieJar()#保存cookie
handler=HTTPCookieProcessor(cookie_jar)#参数cookie
opener=build_opener(handler)
resp=opener.open(rep)
cookie_jar.save('cookie.txt',ignore_discard=True,ignore_expires=True)#【!】保存cookie,在cookie.txt文件夹里
def use_cookie():
info_url='http://learn.open.com.cn/StudentCenter/MyCourse/MyCourseDetail?CourseID=69249&CourseIndex=0'#登录个人中心的url
headers = {"UserAgent": UserAgent().random}
rea=Request(info_url,headers=headers)
cookie_jar=MozillaCookieJar()
cookie_jar.load('cookie.txt',ignore_discard=True,ignore_expires=True)#加载用cookie_jar.load
handler=HTTPCookieProcessor(cookie_jar)
opener=build_opener(handler)
resp=opener.open(rea)
print(resp.read().decode())
if __name__ == '__main__':
get_cookie()
# use_cookie()
老师,我这显示以下错误,上面是我得代码。我搞了一个多小时了,也没整明白,你帮我看看。
D:\pythonDownloads\python.exe E:/demo1/test12/pdemo/15cookie的使用3.py
Traceback (most recent call last):
File "E:/demo1/test12/pdemo/15cookie的使用3.py", line 34, in <module>
get_cookie()
File "E:/demo1/test12/pdemo/15cookie的使用3.py", line 18, in get_cookie
resp=opener.open(rep)
File "D:\pythonDownloads\lib\urllib\request.py", line 531, in open
response = meth(req, response)
File "D:\pythonDownloads\lib\urllib\request.py", line 641, in http_response
'http', request, response, code, msg, hdrs)
File "D:\pythonDownloads\lib\urllib\request.py", line 569, in error
return self._call_chain(*args)
File "D:\pythonDownloads\lib\urllib\request.py", line 503, in _call_chain
result = func(*args)
File "D:\pythonDownloads\lib\urllib\request.py", line 649, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
Process finished with exit code 1