#導入庫
import urllib.request
#獲取單個html文件內容
def getHtml(url):
html=urllib.request.urlopen(url).read()
return html
#將html文件重新命名,保存到指定位置
def saveHtml(file_name,file_content):
#注意Windows文件命名的禁用符,比如/
with open(file_name.replace('/','_')+".html","wb") as f:
f.write(file_content)
#寫文件用bytes而不是str,所以要轉碼
#讀取csv格式的文件,只讀
f = open("commed.csv","r")
count=1
#讀取每一行的數據,每一行的數據逐一處理
for line in f:
count=count+1
a=[]
a.append(line.strip().split(","))
site=a[0][0]
if len(site) > 10:
#滿足條件后,將讀取的每一個網址信息,進行訪問保存,重新命名保存到本地
title="commed\\"+str(count)+"行"+a[0][1]
html=getHtml(site)
saveHtml(title,html)
#打印輸出確認是否保存成功,顯示當前處理數據的行數
print("下載成功"+"===第"+str(count)+"行")
#關閉文件讀取函數
f.close()