[Python] インターネットにアクセスしてみる
こんにちは、@yasuです。
今回はインターネットにアクセスする方法について学習してみたいと思います。
- urlopenメソッドを用いました
urlopenメソッドの位置が、Pythonのバージョン2とバージョン3で、変更になっているので注意。
実行環境
今回は、https://repl.it/ でも Visual Studio Codeでも可能です。
通常は1度インポートしたライブラリを削除する必要はありませんが、いくつかの処理を連続した確認するために、行っています。
コード
import sys
url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345"
#
# Python v2用のコード 「失敗」
# 「urlopen」は「urllib」モジュールにない。
#
try:
import urllib
response = urllib.urlopen(url)
print(response.read())
except:
print(sys.exc_info())
# (<class 'AttributeError'>, AttributeError("module 'urllib' has no attribute 'urlopen'"), <traceback object at 0x046331E8>)
finally:
del urllib
#
# Python v3 「失敗」
# 「request」は「urllib」モジュールにない。
#
try:
import urllib
response = urllib.request.urlopen(url)
print(response.read())
except:
print(sys.exc_info())
#(<class 'AttributeError'>, AttributeError("module 'urllib' has no attribute 'request'"), <traceback object at 0x031CB408>)
finally:
del urllib
#
# Python v3 「成功」
#
try:
import urllib.request
response = urllib.request.urlopen(url)
print(response.read())
#b'and the next nothing is 44827'
finally:
del urllib.request
#
# Python v3 「成功」
#
try:
from urllib import request
response = request.urlopen(url)
print(response.read())
#b'and the next nothing is 44827'
finally:
del request
実行結果
参考サイト
- How to unimport a python module which is already imported?
https://stackoverflow.com/questions/32234156/how-to-unimport-a-python-module-which-is-already-imported
@yasu transfered 0.5 KRWP to @krwp.burn. voting percent : 5.62%, voting power : 63.32%, steem power : 1925970.31, STU KRW : 1200.
@yasu staking status : 250 KRWP
@yasu limit for KRWP voting service : 0.5 KRWP (rate : 0.002)
What you sent : 0.5 KRWP [47279080 - b321b1e8d43a61c222d438ec3445f642bfedda31]