python - 发出 GET 请求,然后用 Python (Twisted) 打印出响应体

标签 python http web twisted twisted.client

在 Twisted 的网站上,他们有一个名为“接收响应”的示例,它向您展示了如何获取响应 header 和响应代码等,但不是响应主体(请求返回到网站的实际 HTML 主体) .

在 def cbrequest(response) 中,我如何打印出 GET 请求返回到 example.com 的 HTML 文本?他们展示了诸如 response.headers 之类的方法来获取 header ,但我还没有看到返回前端正文的方法。

http://twistedmatrix.com/documents/12.1.0/web/howto/client.html#auto9

from pprint import pformat

from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.client import Agent
from twisted.web.http_headers import Headers

class BeginningPrinter(Protocol):
    def __init__(self, finished):
        self.finished = finished
        self.remaining = 1024 * 10

    def dataReceived(self, bytes):
        if self.remaining:
            display = bytes[:self.remaining]
            print 'Some data received:'
        print display
        self.remaining -= len(display)

def connectionLost(self, reason):
    print 'Finished receiving body:', reason.getErrorMessage()
    self.finished.callback(None)

agent = Agent(reactor)
d = agent.request(
    'GET',
    'http://example.com/',
    Headers({'User-Agent': ['Twisted Web Client Example']}),
    None)

def cbRequest(response):
    print 'Response version:', response.version
    print 'Response code:', response.code
    print 'Response phrase:', response.phrase
    print 'Response headers:'
    print pformat(list(response.headers.getAllRawHeaders()))
    finished = Deferred()
    response.deliverBody(BeginningPrinter(finished))
    return finished
d.addCallback(cbRequest)

def cbShutdown(ignored):
    reactor.stop()
d.addBoth(cbShutdown)

reactor.run()

编辑:我尝试打印 response.deliverBody(BeginningPrinter(finished)) 来获取响应文本,但无济于事

最佳答案

当我缩进您的 connectionLost 方法时,它是 BeginningPrinter 上的正确方法,而不仅仅是一个自由 float 函数,这工作正常。不过,我确实在 Twisted 15.4.0 上运行过它,所以也许您应该尝试升级?

关于python - 发出 GET 请求,然后用 Python (Twisted) 打印出响应体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32944246/

相关文章:

javascript - window.location.href 不适用于我的表单

php - 使用链接自动填充另一个表单,可能吗?

windows - 网络蓝牙 - Windows 11 断开连接

python - python中pandas中DataFrame的dropna中的thresh

python - MySQL sql 作为列

java - 在 Java 中使用 HTTP 请求发送 cookie

java - 字符串org.json.JSONException : Unterminated object at character

python - BeautifulSoup 附加

java - 如何在没有 numpy 的情况下将 Python 代码转换为 Java

javascript - 如何使 HTTP 连接保持事件状态?