python 登录csdn,清除token,使用cookies 发送post请求编辑个人资料, 获取返回结果到本地
时间: 2023-06-24 12:05:33 浏览: 55
以下是使用 Python 登录 CSDN,清除 token,使用 cookies 发送 POST 请求编辑个人资料,获取返回结果到本地的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 登录 CSDN
login_url = 'https://passport.csdn.net/v1/register/pc/login/doLogin'
headers_login = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299',
'Referer': 'https://passport.csdn.net/login?code=public'
}
data_login = {
'loginType': '1',
'pwdOrVerifyCode': 'your_password',
'userIdentification': 'your_username',
'uaToken': ''
}
session = requests.session()
response_login = session.post(login_url, headers=headers_login, data=data_login)
# 清除 token
soup = BeautifulSoup(response_login.text, 'html.parser')
token = soup.find('input', attrs={'name': 'csrfmiddlewaretoken'})['value']
session.cookies.clear()
# 使用 cookies 发送 POST 请求编辑个人资料
profile_url = 'https://i.csdn.net/settings/profile'
headers_profile = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299',
'Referer': 'https://i.csdn.net/settings/profile'
}
data_profile = {
'csrfmiddlewaretoken': token,
'nickname': 'new_nickname',
'email': 'new_email@example.com',
'realname': 'new_realname',
'gender': '1',
'birthday': '1990-01-01',
'company': 'new_company',
'job_title': 'new_job_title',
'phone': 'new_phone',
'qq': 'new_qq',
'wechat': 'new_wechat',
'weibo': 'new_weibo',
'github': 'new_github',
'gitee': 'new_gitee',
'description': 'new_description',
'blog': 'new_blog',
'blog_rss': 'new_blog_rss',
'blog_title': 'new_blog_title',
'blog_tagline': 'new_blog_tagline',
'blog_category': 'new_blog_category',
'blog_keywords': 'new_blog_keywords'
}
response_profile = session.post(profile_url, headers=headers_profile, data=data_profile)
# 获取返回结果到本地
with open('profile.html', 'w', encoding='utf-8') as f:
f.write(response_profile.text)
```
注意,代码中的 `your_username` 和 `your_password` 需要替换成你自己的 CSDN 账号和密码,`new_nickname`、`new_email@example.com` 等字段也需要根据实际情况修改。