|
25鱼币
本帖最后由 huangdongdong 于 2021-5-24 17:57 编辑
- import urllib.request
- from http.cookiejar import CookieJar#http.cookiejar是python2中的cookielib(向服务端验证身份)
- import json#
- # 豆瓣的登录页
- loginurl = 'https://accounts.douban.com/j/mobile/login/qrlogin_code'
- # 豆瓣首页
- url = 'https://www.douban.com/'
- # 定制opener,传递cookie
- cookie = CookieJar()
- opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie))
- # 设置headers,模拟浏览器
- headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'}
- # 表单提交参数设置
- data = {
- 'ck':'',
- 'name':'这里填邮箱~QAQ',
- 'password':'这里填密码~QAQ',
- 'remember':'false',
- 'ticket':''
- }
- # get请求的request
- req_get = urllib.request.Request(url,headers=headers)
- # post请求的request
- req_post = urllib.request.Request(loginurl,urllib.parse.urlencode(data).\
- encode('utf-8'),headers)
- # get请求的response
- res_get = opener.open(req_get)
- # post请求的response
- res_post = opener.open(req_post)
- res_html = res_post.read().decode('utf-8')
- # json解码
- res_js = json.loads(res_html)
- # 根据status的值判断是否登录成功
- if res_js['status'] == 'success':
- print('登录成功')
- else:
- print('登录失败')
复制代码- # get请求的request
- req_get = urllib.request.Request(url,headers=headers)
- # post请求的request
- req_post = urllib.request.Request(loginurl,urllib.parse.urlencode(data).\
- encode('utf-8'),headers)
- # get请求的response
- res_get = opener.open(req_get)
- # post请求的response
- res_post = opener.open(req_post)
- res_html = res_post.read().decode('utf-8')
- 这一段代码是什么意思???
复制代码
这一题的解题思路是什么???
这里应该先发送post请求,提交表单数据,获得服务器返回的cookie(自动保存在cookieJar对象中),然后再发送get请求,实现访问登录后的页面,
|
最佳答案
查看完整内容
这里应该先发送post请求,提交表单数据,获得服务器返回的cookie(自动保存在cookieJar对象中),然后再发送get请求,实现访问登录后的页面,
|