cookie就是让服务器知道是同一个人
即辨别身份的
比如你先登录进入到CSDN中
然后复制链接重新打开
会提示你没有登录
另一种解释就是带着账户和密码连接服务器
浏览器的开发者选项中可以看懂cookie
下面的cookie内容是从登录后浏览器中复制的
如果不加cookie会提示无法登录
因为你之前没有登陆过
加了之后就可以登陆了
////////////////////////////////
from urllib.request import Request, urlopen
from fake_useragent import UserAgent
url = "http://www.sxt.cn/index/user.html"
headers = {
"User-Agent": UserAgent().chrome,
"Cookie": "UM_distinctid=163d8c88a6740c-01c2fe892f8d8c-737356c-100200-163d8c88a682a2; 53gid2=10466932807008; 53revisit=1528350416275; 53gid1=10466932807008; acw_tc=AQAAAIktZUa8ZQEAoCEsceTKxzX+LOad; CNZZDATA1261969808=52059414-1528348034-%7C1532407588; PHPSESSID=uh265s5725vojpqdsbagj0n726; visitor_type=old; 53gid0=10466932807008; 53kf_72085067_from_host=www.sxt.cn; 53kf_72085067_keyword=http%3A%2F%2Fwww.sxt.cn%2Findex%2Flogin%2Flogin.html; 53kf_72085067_land_page=http%253A%252F%252Fwww.sxt.cn%252F; kf_72085067_land_page_ok=1"
}
request = Request(url, headers=headers)
response = urlopen(request)
print(response.read().decode())
////////////////////////////////////////////////////////////////
以上是建立在已经登录过的二次登录
现在我们直接登录
这里我用的是CSDN
文件名是dologin
你打开后看右边就会有账号密码
from urllib.request import Request, urlopen
from fake_useragent import UserAgent
from urllib.parse import urlencode
from urllib.request import HTTPCookieProcessor,build_opener
# 登录
#这个URL通过F12network的ALL
# 别忘了勾选Preserve log
#中文意思保留请求日志
#你很好奇为什么有2个request和response
#因为第一个是你为了登录
#第二个是登陆后显示的
#没有第一个就没有第二个
login_url = "https://passport.csdn.net/v1/register/pc/login/doLogin"
headers = {
"User-Agent": UserAgent().chrome,
}
form_data = {
"user": "13509142891",
"password": "2603zawxr123"
}
# 把数据进行编码
f_data = urlencode(form_data).encode()
request = Request(login_url, headers=headers, data=f_data)
#response = urlopen(request) 错误的
handler = HTTPCookieProcessor()
opener = build_opener(handler)
#很有可能代码在此处出错
response = opener.open(request)
# 访问页面
info_url = "https://blog.csdn.net/qq_43776408"
request = Request(info_url, headers=headers)
response = opener.open(request)
print(response.read().decode())
#第二种代码出错
#老师使用的是http网站
#我使用的是https网站
#可能要使用http网站
#代码本身没有错
通过cookie登录以及使用账号密码登录
最新推荐文章于 2024-01-28 21:43:05 发布