python - 使用 pycurl 获取回复的 header 值

标签 python pycurl verbose

我想知道一些在使用 PyCurl 发出请求时捕获和访问回复的 header 信息的方法:

c = pycurl.Curl() 
c.setopt(c.URL,'MY_URL')
c.setopt(c.COOKIEFILE,'cookies')
c.setopt(c.COOKIE,'cookies')
c.setopt(c.POST,1)
c.setopt(c.POSTFIELDS,'MY AUTH VALUES')
c.setopt(c.VERBOSE, True)
b = StringIO.StringIO()
c.setopt(c.WRITEFUNCTION, b.write)
c.perform()

回复将以格式良好的 JSON 格式写入缓冲区 b。

我希望在回复中恢复“位置” header 的值。

尝试使用 curl 时,可以在详细输出中看到此值:

[... Curl output ...]
> GET XXXXXXXXX
[... Request ...]
[... Curl output ...]
< HTTP/1.1 302 Found
[... Other headers ...]
< Location: YYYYYYYYYYYYYYY
[... Rest of reply ...]

如何从 python 中恢复 Location header 的值?

最佳答案

如果非要用PyCurl

然后可以通过一个回调函数来获取header信息:

# code...

# Callback function invoked when header data is ready
def header(buf):
    # Print header data to stderr
    import sys
    sys.stderr.write(buf)
    # Returning None implies that all bytes were written

# more code...

c.setopt(pycurl.HEADERFUNCTION, header)

# yet more code...

the docs 中了解更多信息.

你也可以使用requests代替pycurl

虽然这可能不可能,也不能直接回答您的问题,但我建议您使用 requests library而不是 pyCurl:

import requests

payload = {"key":"value"}
cookies = {"key":"value"}

r = requests.post('https://my.example.com', data=payload, cookies=cookies)

location = r.headers["Location"]
content  = r.text

print(content)

这将使您的生活更加轻松。通过 reading the docs 了解更多信息

关于python - 使用 pycurl 获取回复的 header 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15641080/

相关文章:

python - 发送包含自定义数据的 SNMP 陷阱

python - 如何使用 Python 解析复杂的文本文件?

python - PycURL 的替代品?

Python——Curl 可以工作,而 requests lib 不行

powershell - 改变 Powershell session 中每个 cmdlet 的行为以传递详细标志

python - 模型字段 "verbose name"的使用

python - 列表理解返回值加上 [None, None, None],为什么?

python - Lark 解析器无法解析字符,即使它们是在规则的正则表达式中定义的

python - pycurl https 错误 : unable to get local issuer certificate

php - MySQL任务的即时可视化