天天看點

Python使用requests爬取一個網頁并儲存

#導入 requests子產品
import requests
#設定請求頭,讓網站監測是浏覽器
headers = {
\'user-agent\': \'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3573.0 Safari/537.36\',
}
# 爬取網頁的URL http://www.kdhj-edu.net/
r = requests.get(\'http://www.kdhj-edu.net/\',headers=headers)
#擷取目前編碼 目前編碼有utf-8 ISO-8859-1
print(r.encoding)
# 建立一個檔案名 例如:TencentHtml 設定檔案格式編碼為 utf-8
# 注意檔案格式的編碼和 擷取的編碼 要一緻,不然出現亂碼問題
f = open("TencentHtml", "w",encoding="ISO-8859-1")
for i in r.text:
    #将資料寫入檔案
    f.write(i)
#關閉檔案
f.close()      
Python使用requests爬取一個網頁并儲存