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