教你用python3怎么寫這個小程序???
現在都用python3了,老師還用2來教,這里無私地提供python3的版本,希望對大家有幫助。
先簡單講解下,python3中已經統一只有一個urllib庫了,所以沒有老師講的那么復雜。
另外注意:python3中的urlopen方法在urllib.request庫下,注意使用時不要導錯包了。
直接上代碼吧。
from?urllib?import?request,?parse URL_IP?=?"http://httpbin.org/ip" URL_GET?=?"http://httpbin.org/get" def?use_simple_urllib(): response?=?request.urlopen(URL_IP) print(">>>>Response?Headers:") print(response.info()) print(">>>>Response?Body:") print(response.read().decode('utf-8')) def?use_params_urllib(): #?構建請求參數 params?=?parse.urlencode({'param1':?'hello',?'param2':?'world'}) print("Request?Params:") print(params) #?發送請求 response?=?request.urlopen("?".join([URL_GET,?"%s"])?%?params) #?處理響應 print(">>>>Response?Headers:") print(response.info()) print(">>>>Response?Body:") print(response.read().decode('utf-8')) if?__name__?==?'__main__': print(">>>Use?simple?urllib:") use_simple_urllib() print(">>>Use?params?urllib") use_params_urllib()
urlopen方法返回的是HttpResponse對象,這個對象的方法getheaders()以列表形式返回頭部信息,也可以用info(),打印效果跟老師一樣,更好看些。
因為HttpResponse對象不能迭代,所以不能用老師的那個方法,只能用read()方法讀出信息,再用decode()用utf-8格式解碼出來!
python3中的urlencode方法在urllib.parse庫里面。
喜歡python的朋友可以加我的口口群交流:146202960
2019-03-15
都是大佬,像我直接就在jupyter上又裝了個python2...
2017-08-12
<p>這是輸出結果:</p>
2017-04-07
補一個完整的截圖