本文實例講述了Python實現從Web的一個URL中抓取文檔的方法,分享給大家供大家參考。具體方法分析如下:
實例代碼如下:
import urllib doc = urllib.urlopen("http://www.python.org").read() print doc#直接打印出網頁 def reporthook(*a): print a #將http://www.renren.com網頁保存到renre.html中,#每讀取一個塊調用一字reporthook函數 urllib.urlretrieve("http://www.renren.com",'renren.html',reporthook) #將http://www.renren.com網頁保存到renre.html中 urllib.urlretrieve("http://www.renren.com",'renren.html')
程序運行結果如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">..........................網頁內容</body></html>(0, 8192, -1)(1, 8192, -1)(2, 8192, -1)
其中urllib.urlopen返回一個類文件對象。
希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答