Challenge
Submit the captcha before the two-second deadline.
在两秒时限内提交验证码。
https://webhacking.kr/challenge/code-4/Analysis
GET 响应同时给出本次页面实例的 captcha 和 st Cookie。服务端用 st 判断时限,并要求 POST 的 captcha 与本次页面生成的值相同;因此 GET 和 POST 必须使用同一个 requests.Session。不能预先保存验证码,也不能把下一次 GET 得到的 st 与旧验证码混用。
Solution
下面的脚本完整完成一次 GET、解析 captcha、复用 Cookie 并构造 POST。它只打印响应,不包含账号或固定 session 值:
import re
import requests
URL = "https://webhacking.kr/challenge/code-4/"CAPTCHA_PATTERN = re.compile( r"<input[^>]+name=[\"']?captcha_[\"']?[^>]+value=[\"']([^\"']+)[\"']", re.IGNORECASE,)
def extract_captcha(html): match = CAPTCHA_PATTERN.search(html) if not match: raise RuntimeError("captcha input was not found") return match.group(1)
def solve_once(): with requests.Session() as session: response = session.get(URL, timeout=10) response.raise_for_status()
captcha = extract_captcha(response.text) if "st" not in session.cookies: raise RuntimeError("st cookie was not set by the GET response")
post_response = session.post( URL, data={"id": "demo", "cmt": "hello", "captcha": captcha}, timeout=10, ) post_response.raise_for_status() return post_response
if __name__ == "__main__": result = solve_once() print(result.status_code) print(result.text)