使用Python Requests库登录Twitter遇400错误,求解决方法
解决Twitter登录的400错误(仅使用Requests库)
首先,你的代码里有几个关键问题导致了400 Bad Request响应,我来一步步帮你梳理和修正:
1. 请求方法错误:用了GET而非POST
登录表单的提交必须使用POST请求,而你用了requests.get(),这是最核心的错误——GET请求不会把payload作为表单数据提交,自然会被服务器拒绝。
2. Payload的问题
- 重复的
authenticity_token字段:你的payload里出现了两次这个键,这会导致参数解析失败,必须删除其中一个。 - 硬编码
authenticity_token:这个token是Twitter动态生成的,每次访问登录页面都会变化,硬编码旧token肯定会失效。你需要先请求登录页面,从页面的HTML中提取这个值。 - 冗余参数:
ui_metrics这类参数是Twitter前端生成的追踪数据,很多时候可以省略,不会影响登录;另外lang留空也没问题,但确保没有多余的无效字段。
3. Cookie和Headers的问题
- 硬编码Cookie:Cookie是会话相关的,硬编码旧Cookie会导致会话不匹配。正确的做法是先请求登录页面,获取服务器返回的Cookie,再带着这个Cookie发送登录请求。
- 缺少
Content-Type头:提交表单时需要指定Content-Type: application/x-www-form-urlencoded,否则服务器无法正确解析你的payload。
修正后的完整代码
import requests from bs4 import BeautifulSoup # 会话对象,自动处理Cookie session = requests.Session() headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36", "accept-language": "en-US,en;q=0.9", "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "content-type": "application/x-www-form-urlencoded" } # 第一步:获取登录页面,提取authenticity_token和Cookie login_page_url = "https://twitter.com/login" login_page_response = session.get(login_page_url, headers=headers) soup = BeautifulSoup(login_page_response.text, "html.parser") # 从表单隐藏字段中提取authenticity_token authenticity_token = soup.find("input", {"name": "authenticity_token"})["value"] # 第二步:构造正确的Payload payload = { "session[username_or_email]": "你的账号/邮箱", "session[password]": "你的密码", "authenticity_token": authenticity_token, "remember_me": "1", "redirect_after_login": "/" } # 第三步:发送POST请求到登录接口(注意接口是/sessions,不是/login) login_post_url = "https://twitter.com/sessions" login_response = session.post(login_post_url, data=payload, headers=headers) # 验证登录结果 print("响应状态码:", login_response.status_code) print("跳转后的URL:", login_response.url) # 检查是否登录成功:比如访问首页看是否包含你的用户名 home_response = session.get("https://twitter.com/home", headers=headers) if "你的用户名" in home_response.text: print("登录成功!") else: print("登录失败,可能需要处理验证码或账号验证步骤")
额外注意事项
- Twitter有严格的反爬机制,如果频繁请求可能会触发验证码或账号验证,这时候仅用Requests库可能无法绕过(需要手动处理验证码,但这超出了纯Requests的范围)。
- 确保你的账号没有开启双重验证,如果开启了,登录时还需要额外的验证码参数,这也需要你手动处理。
- 尽量模拟真实浏览器的行为,比如不要频繁发送请求,保持headers的一致性。
内容的提问来源于stack exchange,提问作者Akhil Reddy
相关产品推荐
相关产品推荐

