请求python库,返回方法中的会话
正在尝试在python中的方法中返回请求库会话。。。 这看起来很简单,我的脚本工作得很好,然后我将它清理成一个类和方法,但它不会工作,会话似乎不能从方法返回?我很困惑,因为我相信这应该是这样的 这是更改前的代码,它工作正常:请求python库,返回方法中的会话,python,session,post,get,request,Python,Session,Post,Get,Request,正在尝试在python中的方法中返回请求库会话。。。 这看起来很简单,我的脚本工作得很好,然后我将它清理成一个类和方法,但它不会工作,会话似乎不能从方法返回?我很困惑,因为我相信这应该是这样的 这是更改前的代码,它工作正常: import requests httpHeaders = { 'Host' : 'www.somesite.com', 'User-Agent' : 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:16.0) Gecko/20
import requests
httpHeaders = { 'Host' : 'www.somesite.com',
'User-Agent' : 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:16.0) Gecko/20100101 Firefox/16.0',
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language' : 'en-US,en;q=0.5',
'Accept-Encoding' : 'gzip, deflate',
'Connection' : 'keep-alive',
'Referer' : 'https://blah.someloginsite.com/logon',
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length' : '59',
'Referer' : 'someurl.com'}
postContent = { 'UserName': 'blabhbhbhb',
'Password': 'qwerty',
'submit' : '',
'returnUrl' : ''}
s = requests.Session()
s.post('https://blah.someloginsite.com/logon', data=postContent, headers=httpHeaders)
param = {'someID': '225', 'anotherID': '0'}
r = s.post('https://someurl/doactionthatneedslogin', data=param)
print r.status_code
print r.headers['content-type']
print r.encoding
print r.text
上面的代码工作得很好,但当我将其分解为类和函数/方法时,它将不起作用。现在我清理了代码,但它不起作用,似乎我无法在请求库中返回会话,但我确信我可以
import requests
class doit():
def __init__(self, username, password):
print "test"
spSession = self.getSession(username, password)
self.doAction(spSession, 33, 4)
#Initializes session
def getSession(self, username, password):
httpHeaders = {SAME AS ABOVE BLAHBLAHBLAH}
postContent = { 'UserName': username ,
'Password': password ,
'submit' : '',
'returnUrl' : ''}
s = requests.Session()
s.post('https://someurl.com/logon', data=postContent, headers=httpHeaders)
return s
def doAction(self, spSession, someid,anotherid):
param = {'someid': someid , 'anotherid': anotherid}
r = spSession.post('https://someurl/doactionthatneedslogin', data=param)
print r.status_code
print r.headers['content-type']
print r.encoding
print r.text
doit("usernameas","qwerty")
知道发生了什么事吗?第一个剧本成功了;而第二个没有。我所做的就是把它清理干净。
我想要它,这样我就可以用不同的方法反复使用会话
第二个脚本确实与登录一起工作,因此会话似乎很好,但第二个操作即使已登录也无法按预期工作。好吧,这两个示例似乎使用了不同的参数,但我能看到的唯一显著区别是第一个示例中的这一行之间
param = {'someID': '225', 'anotherID': '0'}
self.doAction(spSession, 33, 4)
…第二个例子中的这一行
param = {'someID': '225', 'anotherID': '0'}
self.doAction(spSession, 33, 4)
…其中第一个参数使用字符串,第二个参数使用整数。如果你把第二行改成
self.doAction(spSession, '33', '4')