2009-01-23 77 views

回答

27

有幾種解決方案(默認情況下,它們被丟棄)。以下是使用HEADERFUNCTION選項的 示例,可讓您指定 函數來處理它們。

其他解決方案是WRITEHEADER選項(與 WRITEFUNCTION不兼容)或將HEADER設置爲True,以便將它們傳送到身體上 。

#!/usr/bin/python 

import pycurl 
import sys 

class Storage: 
    def __init__(self): 
     self.contents = '' 
     self.line = 0 

    def store(self, buf): 
     self.line = self.line + 1 
     self.contents = "%s%i: %s" % (self.contents, self.line, buf) 

    def __str__(self): 
     return self.contents 

retrieved_body = Storage() 
retrieved_headers = Storage() 
c = pycurl.Curl() 
c.setopt(c.URL, 'http://www.demaziere.fr/eve/') 
c.setopt(c.WRITEFUNCTION, retrieved_body.store) 
c.setopt(c.HEADERFUNCTION, retrieved_headers.store) 
c.perform() 
c.close() 
print retrieved_headers 
print retrieved_body 
+0

我想使用它而不必檢索內容。有沒有辦法做到這一點?我的內容很大(1.4GB或類似),我只需要知道大小,而不是內容。 – Alfe 2013-02-20 15:12:24

+0

@Alfe試圖讓```HEAD```請求代替``GET```,就像```c.setopt(pycurl.CUSTOMREQUEST,「HEAD」)``` – Serge 2014-12-05 14:35:08

+0

哇,這是一個晚了後續,但無論如何謝謝你。但現在很久以前了......可能是因爲我這樣做了,但實際上,我不記得: - } – Alfe 2014-12-05 20:50:26

1

這可能會或可能不適合你的選擇:

import urllib 
headers = urllib.urlopen('http://www.pythonchallenge.com').headers.headers 
6

哪吒互生,human_curl用法:PIP human_curl

In [1]: import human_curl as hurl 

In [2]: r = hurl.get("http://stackoverflow.com") 

In [3]: r.headers 
Out[3]: 
{'cache-control': 'public, max-age=45', 
'content-length': '198515', 
'content-type': 'text/html; charset=utf-8', 
'date': 'Thu, 01 Sep 2011 11:53:43 GMT', 
'expires': 'Thu, 01 Sep 2011 11:54:28 GMT', 
'last-modified': 'Thu, 01 Sep 2011 11:53:28 GMT', 
'vary': '*'} 
8
import pycurl 
from StringIO import StringIO 

headers = StringIO() 

c = pycurl.Curl() 
c.setopt(c.URL, url) 
c.setopt(c.HEADER, 1) 
c.setopt(c.NOBODY, 1) # header only, no body 
c.setopt(c.HEADERFUNCTION, headers.write) 

c.perform() 

print headers.getvalue() 

根據需要添加任何其他捲曲setopts /所需的,如FOLLOWLOCATION。