標籤:std http split 刪除 join url python nbsp query
#encoding=utf-8from urllib.request import urlopenimport randomimport os‘‘‘1. 定義一個fuc(url, folder_path) 擷取url地址的內容,儲存到folder_path的檔案目錄下,並隨機產生一個檔案名稱。‘‘‘def save_url_content(url,folder_path=None): if not (url.startswith(‘http://‘) or url.startswith(‘https://‘) ): return u‘url地址不符合規格‘ if not os.path.isdir(folder_path): return u‘folder_path非檔案夾‘ d = urlopen(url) content = d.read() rand_filename = ‘test_%s‘%random.randint(1,1000) file_path = os.path.join(folder_path,rand_filename) d = open(file_path,‘wb‘) d.write(content) d.close() return file_pathprint (save_url_content(‘http://www.baidu.com‘,‘tmp‘))‘‘‘3. 定義一個func(url),分析該url內容裡有多少個連結。 ‘‘‘def get_url_count(url): if not (url.startswith(‘http://‘) or url.startswith(‘https://‘) ): return u‘url地址不符合規格‘ d = urllib.urlopen(url) content = d.read() return len(content.split(‘<a href=‘)) - 1 # str 到bytes 而精緻沒解決print (get_url_count(‘http://hi.baidu.com/jxq61/item/149d29cc8d52513d4594168f‘))‘‘‘2. 定義一個func(folder_path),合并該目錄下的所有檔案,產生一個all.txt。‘‘‘def merge(folder_path): if not os.path.exists(folder_path): return ‘not exists‘ for f in os.listdir(folder_path): file_path = os.path.join(folder_path,f) if os.path.isdir(file_path): merge(file_path) else: merge_file = open(‘merge_test‘,‘ab+‘) content = open(file_path,‘rb‘).read() merge_file.write(content) merge_file.close()merge(‘tmp‘)‘‘‘4. 定義一個func(url), 擷取他?後的參數,並返回成一個dict。‘‘‘import urlparse# urlparse模組主要是把url拆分為6部分,並返回元組。# urllib.parse.urlparse(urlstring, scheme=‘‘, allow_fragments=True)def qs(url): query = urlparse.urlparse(url).query return dict([(k,v[0]) for k,v in urlparse.parse_qs(query).items()])print (qs(‘http://126.com‘))print (qs(‘http://api/api?f=5&g=6&y=5‘))print (qs(‘http://api/api?11=53‘))
‘‘‘5. 定義一個func(folder),刪除該folder下的所有檔案。50421 ‘‘‘
#使用遞迴去解決def delete(folder_path):##習題5 if not os.path.exists(folder_path): return ‘not exists‘ for f in os.listdir(folder_path): file_path = os.path.join(folder_path,f) if os.path.isdir(file_path): delete(file_path) else: os.remove(file_path)delete(‘/tmp/5‘)
Python 函數習題