2016-07-22 109 views
0

我做了一個登錄系統來實驗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,如果你查看源代碼,它不是空白

回答

1

你不能以這種方式檢索用PHP定義的會話變量:

會話是一種存儲跨越多個頁面的信息(在變量中)的方式,用於在多個頁面上使用 。

與cookie不同,信息不存儲在用戶計算機上。

來源:http://www.w3schools.com/php/php_sessions.asp

正則表達式替代

可選擇使用正則表達式,你可以使用BeautifulSoupdocs)提取令牌值:

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'] 
+0

謝謝克里斯托夫。得到它了。但給我一點:如果它沒有存儲在我的電腦中,如果我從瀏覽器中刪除我的cookies /歷史記錄,我的會話也會被銷燬? – Miguel