会话cookie和http头
问题描述:
我做了一个登录系统来实验python登录脚本,登录系统有一个表单令牌,我用正则表达式从页面中提取出来(所以我可以在用户名/密码后发布它),那就是我想要避免的。所以我做了这个示例代码向你展示,也许你可以激怒我。无论如何除了这个提取session
增值税。会话cookie和http头
我的PHP代码:
<?php
session_start();
$_SESION['token'] = md5(time());
?>
<input type="hidden" name="token" value="<?= $_SESION['token']; ?>">
我的 '登录脚本'(只是相关的有关令牌extracion部分):在
import requests
import re
s = requests.Session()
headers = {
"User-agent" : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1',
"Referer": 'https://www.google.com'
}
req = s.get('http://migueldvl.com/heya/login/tests.php', headers=headers)
token = re.compile('<input type="hidden" name="token" value="(.*?)">').search(req.text).group(1)
print('page: ', req.text)
print('token: ', token)
print('\nheaders we sent: ', req.request.headers)
print('\nheaders server sent back: ', req.headers) # (nothing about the token session here)
你们,欢迎测试代码(python3)这个url,如果你查看源代码,它不是空白
答
你不能以这种方式检索用PHP定义的会话变量:
会话是一种存储跨越多个页面的信息(在变量中)的方式,用于在多个页面上使用 。
与cookie不同,信息不存储在用户计算机上。
来源:http://www.w3schools.com/php/php_sessions.asp
正则表达式替代
可选择使用正则表达式,你可以使用BeautifulSoup(docs)提取令牌值:
from bs4 import BeautifulSoup
r = s.get('http://migueldvl.com/heya/login/tests.php', headers=headers)
r.raise_for_status()
soup = BeautifulSoup(r.content, 'lxml')
# Simple reference
token = soup.html.body.input['value']
# With more attributes specified
token = soup.html.body.find('input', attrs={'name':'token', 'type':'hidden'})['value']
谢谢克里斯托夫。得到它了。但给我一点:如果它没有存储在我的电脑中,如果我从浏览器中删除我的cookies /历史记录,我的会话也会被销毁? – Miguel