会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 133940个问题
Python 全系列/第十六阶段:Python 爬虫开发/爬虫反反爬- 1067楼
Python 全系列/第十六阶段:Python 爬虫开发/爬虫反反爬- 1070楼

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


Python 全系列/第十六阶段:Python 爬虫开发/scrapy框架使用(旧) 1072楼
Python 全系列/第十六阶段:Python 爬虫开发/爬虫基础(旧) 1073楼
Python 全系列/第十六阶段:Python 爬虫开发/爬虫基础(旧) 1074楼
Python 全系列/第十六阶段:Python 爬虫开发/爬虫基础(旧) 1077楼
Python 全系列/第十六阶段:Python 爬虫开发/爬虫基础(旧) 1078楼
Python 全系列/第十六阶段:Python 爬虫开发/移动端爬虫开发- 1079楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637