如何使用Python的urlopen()方法获取HTTP响应头

3
在这段代码中
from bs4 import BeautifulSoup
import urllib2
import re

html_page = urllib2.urlopen("http://fr.wikipedia.org/wiki/Alan_Turing")

soup = BeautifulSoup(html_page, "lxml")

print soup

我可以返回源代码。

但是如何使用Python获取http头呢?

例如:

HTTP/1.1 200 OK
Server: nginx/1.9.4
Date: Thu, 10 Sep 2015 09:13:25 GMT
Content-Type: text/css; charset=utf-8
Content-Length: 10699
x-content-type-options: nosniff
Cache-Control: public, max-age=300, s-maxage=300
X-Powered-By: HHVM/3.6.5
Access-Control-Allow-Origin: *
Vary: Accept-Encoding
Expires: Thu, 10 Sep 2015 09:16:07 GMT
Content-Encoding: gzip
Accept-Ranges: bytes
Age: 138

感谢!
1个回答

3
根据文档urllib2.urlopen方法返回一个对象,并且该对象含有一个info()方法来获取头信息。
response = urllib2.urlopen("http://fr.wikipedia.org/wiki/Alan_Turing")
info = response.info()
for header in info.headers:
    print header,

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接