2014-09-30 61 views
0

我試圖讓一個機器人登錄到phpbb3論壇,我可以在urllib。但是,因爲它需要會話ID等,所以在更改頁面時它不會保持登錄狀態(我認爲這是問題)。所以我試圖使用requests,但我甚至無法登錄requests,即使它易於使用urllib登錄。爲什麼這個基本的urllib代碼工作,但這個基本的請求代碼不是?

#!/usr/bin/env python3 

import urllib 
import http.cookiejar 
from bs4 import BeautifulSoup 

username = '' 
password = '' 

cj = http.cookiejar.CookieJar() 
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) 
opener.addheaders = [('User-agent','Mozilla/5.0')] 

auth_url = "http://www.mingeford365.co.uk/forum/ucp.php?mode=login" 
payload = {'username' : username, 'password' : password, 
      "autologin" : "on", 'login' : 'Login'} 

data = urllib.parse.urlencode(payload) 
binary_data = data.encode('UTF-8') 

req = urllib.request.Request(auth_url,binary_data) 
resp = urllib.request.urlopen(req) 
contents = resp.read().decode('UTF-8') 

if username in contents: 
    print('logged in.') 

上述代碼有效。以下請求代碼不起作用

#!/usr/bin/env python3 
import requests 
from bs4 import BeautifulSoup 

url = 'http://www.mingeford365.co.uk/forum/ucp.php?mode=login' 

logininfo = {'username': '', 
      'password': '', 
      'autologin' : "on", 
      'login' : 'Login'} 

headers = {'User-Agent' : 'Mozilla/5.0 (x11; Ubuntu; Linux x86; rv:28.0) Gecko/20100101 Firefox/28.0'} 
      #'Accept': 'text/html, application/xhtml+xhtml,application/xml;q=0.9,*/*;q=0.8', 
      #'Accept-Language': 'en-gb,en;q=0.5', 
      #'Accept-Encoding': 'gzip, deflate',         
      #'referer': 'http://www.mingeford365.co.uk/forum/index.php', 
      #'Connection' : 'keep-alive', 
      #'Content-Type': 'application/x-www-form-urlencoded'} 

session = requests.Session() 
get_session_id = session.get("http://www.mingeford365.co.uk/forum",headers=headers) 
print(get_session_id.status_code) 

response = session.post(url,params=logininfo,headers=headers) #cookies=get_session_id.cookies 
soup = BeautifulSoup(response.text) 

print(soup.get_text()) 
+0

你確定你是要通過將LoginInfo – 2014-09-30 10:12:50

+0

你能提供更精確的問題陳述不是*「不起作用」 *的正確方法? – jonrsharpe 2014-09-30 10:15:18

回答

0

您正在將您的POST正文參數放入您的URL中。使用data,不params

response = session.post(url, data=logininfo, headers=headers) 
相關問題