python根據url獲取網頁內容

#! /usr/bin/python
# -*- coding:utf-8 -*-
'''
Created on 2013-11-5

@author: Java
'''
import urllib2
import time
import socket
from sgmllib import SGMLParser

class WebUtil():
    def __init__(self):
        self.trytims = 3
        pass

#讀取Url 內容
#     timeout=10
#     socket.setdefaulttimeout(timeout)#這裏對整個socket層設置超時時間。後續文件中如果再使用到socket,不必再設置
#     sleep_download_tine=10
#     time.sleep(sleep_download_tine)
    def readUrl(self,url):
        try:
            request = urllib2.Request(url,headers = {'User-Agent':'Magic Browser'})
            webpage = urllib2.urlopen(url)
            content = webpage.read()
            
            return content
            request.close()
        except Exception,errmg:
            print '讀取失敗:%s'%errmg
            return None
        
if __name__=='__main__':
    web = WebUtil()
    content = web.readUrl('http://www.haodf.com/doctor/DE4rO-XCoLUOzseHcTieBvzKOb.htm')
    print content
    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章