2012-06-08 31 views
0

我正在研究使用python來檢索html和http頭信息而不是進行2個單獨調用的單個http請求的可能性。使用Python從單個請求獲取html和頭文件

任何人都知道有什麼好方法嗎?

此外,不同的製作這些請求的方法之間的性能差異如何urllib2和httpconnection等

回答

3

只需使用urllib2.urlopen()。可以通過調用返回對象的read()方法來檢索HTML,並且可以在headers屬性中使用標題。

import urllib2 
f = urllib2.urlopen('http://www.google.com') 

>>> print f.headers 
Date: Fri, 08 Jun 2012 12:57:25 GMT 
Expires: -1 
Cache-Control: private, max-age=0 
Content-Type: text/html; charset=ISO-8859-1 
Server: gws 
X-XSS-Protection: 1; mode=block 
X-Frame-Options: SAMEORIGIN 
Connection: close 

>>> print f.read() 
<!doctype html><html itemscope itemtype="http://schema.org/WebPage"><head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> 
... etc ... 
1

如果您使用HTTPResponse您可以使用兩個函數調用標題和內容,但它不會使兩次到服務器。

相關問題