之前訪問百度的時候,代碼總會出現請求超時,不知道什么原因,學了的https后,解決了這個問題:
import urllib import urllib.request import ssl #導入Python SSL處理模塊 #如果網站的SSL證書是經過CA認證,就需要單獨處理SSL證書,讓程序忽略SSL證書驗證錯誤,即可正常訪問 context = ssl._create_unverified_context() #忽略安全 url="https://www.baidu.com" headers={"User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE"} # url 作為Request()方法的參數,構造並返回一個Request對象 request=urllib.request.Request(url,headers=headers) #Request對象作為urlopen()方法的參數,發送給服務器並接收響應 #在urlopen()方法里 指明添加 context 參數 response=urllib.request.urlopen(request,context=context).read() print(response.decode("utf-8"))