[Python] インターネットにアクセスしてみる

in SCT.암호화폐.Crypto5 years ago (edited)

こんにちは、@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

実行結果

image.png

参考サイト

Sort:  

@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]

Coin Marketplace

STEEM 0.12
TRX 0.34
JST 0.033
BTC 121982.72
ETH 4430.07
BNB 1308.89
SBD 0.78