我想知道一些在使用 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/