# python3導入request包
from urllib import request
import sys
import io
# 若是須要用print打印時,若是出現異常能夠先設置輸出環境
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# 須要獲取的url
url = 'http://www.jinri.com/'
# 頭文件
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"
}
# 生成請求對象
req = request.Request(url, headers=headers)
# 調用request的urlopen方法發起請求,並返回結果對象,若是沒有data參數時,則是get請求,不然是post請求
response = request.urlopen(req)
# 將結果寫入html文件中,
with open('a.html', 'wb') as f:
f.write(response.read())
# 打印返回的狀態碼
print(response.getcode())
# 打印返回的url,防止重定向url變化
print(response.url)