下面是我添加cookie以使用getPage获取页面的代码。也是我收到的错误消息。如何添加cookie?如果cookie是None,则代码可以正常工作。
cj = cookielib.CookieJar()
client.getPage(iUrl,headers,method='GET',cookies=cj).addCallback(self.processPage,iUrl).addErrback(self.printError,iUrl)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 84, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 69, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 59, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 37, in callWithContext
return func(*args,**kw)
--- <exception caught here> ---
File "/usr/lib/python2.7/dist-packages/twisted/internet/selectreactor.py", line 146, in _doReadOrWrite
why = getattr(selectable, method)()
File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 664, in doConnect
self._connectDone()
File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 671, in _connectDone
self.protocol.makeConnection(self)
File "/usr/lib/python2.7/dist-packages/twisted/internet/protocol.py", line 459, in makeConnection
self.connectionMade()
File "/usr/lib/python2.7/dist-packages/twisted/web/client.py", line 61, in connectionMade
for cookie, cookval in self.factory.cookies.items():
exceptions.AttributeError: CookieJar instance has no attribute 'items'
*--- Failure #133 ---
Failure: exceptions.AttributeError: CookieJar instance has no attribute 'items'
*--- End of Failure #133 -
答案 0 :(得分:2)
看起来你在cookie参数中传递cookiejar
。我无法找到有关工作的参考资料。
我尝试过一个简单的dict
并且它有效。这是完整的代码:
from twisted.web import client
import pprint
def processPage (page, url):
print len(page), 'bytes received'
print 'cookies: ', pprint.pformat(cj)
def printError(error, url):
print 'ERROR: ', error.getErrorMessage()
def end(ignore):
reactor.stop()
iUrl = 'http://twistedmatrix.com'
headers = []
cj = {}
client.getPage(iUrl,headers,method='GET',cookies=cj).addCallback(processPage,iUrl).addErrback(printError,iUrl).addBoth(end)
from twisted.internet import reactor
reactor.run()
这是输出:
10660 bytes received
cookies:
{'trac_form_token': '940bfe8055b63872303017ba',
'trac_session': '5a3500ec1bc8efad40974a31'}