python3使用urllib示例
最簡單的例子
import urllib.request with urllib.request.urlopen('http://python.org/') as response: html = response.read()
取回一個資源并臨時保存
import urllib.request local_filename, headers = urllib.request.urlretrieve('http://python.org/') html = open(local_filename)
import urllib.requestreq = urllib.request.Request('
使用POST方法發送數據, 數據需要先經過編碼
import urllib.parse import urllib.request使用GET方法發送數據, 數據需先經過編碼
>>> import urllib.request >>> import urllib.parse >>> data = {} >>> data['name'] = 'Somebody Here' >>> data['location'] = 'Northampton' >>> data['language'] = 'Python' >>> url_values = urllib.parse.urlencode(data) >>> print(url_values) # The order may differ from below. name=Somebody+Here&language=Python&location=Northampton >>> url = 'http://www.example.com/example.cgi' >>> full_url = url + '?' + url_values >>> data = urllib.request.urlopen(full_url)添加HTTP header, 指定user-agent
import urllib.parse import urllib.request處理異常
>>> req = urllib.request.Request('http://www.pretend_server.org') >>> try: urllib.request.urlopen(req) ... except urllib.error.URLError as e: ... print(e.reason) ... (4, 'getaddrinfo failed')
>>> req = urllib.request.Request('http://www.python.org/fish.html') >>> try: ... urllib.request.urlopen(req) ... except urllib.error.HTTPError as e: ... print(e.code) ... print(e.read()) ... 404 b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html ... <title>Page Not Found</title>\n ...
參考
參考
本文由用戶 lai123 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!