227:HTTPクライアントを作る
おまけ
HTTPサーバを作る
http://mylesbraithwaite.com/tumblelog/post/485/
認証の例
http://blog.livedoor.jp/kato_taka_special/archives/50908403.html
最も簡単なのは、urllib2モジュールを使うことです。何と2行で任意のページが取り込めます。例では、yahooジャパンのhtmlファイルを取って、その中である文字列を含む行だけをプリントしています。正規表現を使えば複雑なパターンから情報を取り出せます。ソースの中で文字列を示すシングルコーテーションとかが消えているので、エディットモードで見てください。
>>> import urllib2
>>> for line in urllib2.urlopen('http://www.yahoo.co.jp'):
if 'All Rights Reserved' in line:
print line
2005 Yahoo Japan Corporation. All Rights Reserved.
次の例は、Proxyサーバを利用した場合である。これは、会社のコードを与えることによりyahooのhtmlから正規表現で株価を取るものである。このときはpythonのバージョンが2.1でProxyを明示的に指定できなかったため、FanclyURLOpenerというのを使った。多分、今ならこんなことはしなくていいと思う。proxyのアドレスはhogehoge:8080としてある。
def getKabuka(code):
import urllib
from re import search
proxies = proxies={'http': 'http://hogehoge:8080'}
opener = urllib.FancyURLopener(proxies)
url='http://quote.yahoo.co.jp/q?s='+code+'&d=t'
string='取引値<br>(.+)<b>(.+)</b></td><td nowrap>前日比<br>'
try: ##エラーの処理
f=opener.open(url) ##urlをオープン
except IOError, (errno, strerror): ##オープンできないときは
out= 'web error'
else: ##オープンできたら
##f=open('c:/temp/kabukasjis.html','r')
txt=f.read() ##htmlファイルを読み込む
m=search(string,txt) ##パターンマッチングでサーチ
out= m.group
return out
proxyを使わないで直接接続する例
# -*- coding: cp932 -*-
def getKabuka(code):
import urllib2
from re import search
##code='4753'
url='http://quote.yahoo.co.jp/q?s='+code+'&d=t'
print url
string='取引値<br>(.+)<b>(.+)</b></td><td nowrap>前日比.+>(.+?)\(.+\)<.+>時価総額<br>(.+)百万円 <'
try: ##エラーの処理
f=urllib2.urlopen(url) ##urlをオープン
except IOError, (errno, strerror): ##オープンできないときは
out= 'web error'
else: ##オープンできたら
txt=f.read() ##htmlファイルを読み込む
##print unicode(txt,'euc_jp') ##変換できないコードがあるらしくエラーになる
m=search(string.encode('euc_jp'),txt) ##パターンマッチングでサーチ Windowsの場合は検索文字をEUCに変換してから
out= m.group
return out
a=getKabuka('4753')
for i in range(5):
print unicode(a(i),'euc_jp')
こんな答えが得られる
>>> http://quote.yahoo.co.jp/q?s=4753&d=t 取引値<br>15:00 <b>336</b></td><td nowrap>前日比<br><font color=ff0020>-80 (-19.23%)</font></td><td nowrap >前日終値<br>416</td><td nowrap>出来高<br>152,433</td><td nowrap>時価総額<br>352,516百万円< 15:00 336 -80 352,516
普通はhttplibを直接インポートはしないが、こんなふうにするとデバッグもできる。
>>> import httplib
>>> httplib.HTTPConnection.debuglevel = 1
>>> import urllib
>>> feeddata = urllib.urlopen('http://diveintomark.org/xml/atom.xml').read()
connect: (diveintomark.org, 80)
send: 'GET /xml/atom.xml HTTP/1.0\r\nHost: diveintomark.org\r\nUser-agent: Python-urllib/1.15\r\n\r\n'
reply: 'HTTP/1.1 410 Gone\r\n'
header: Date: Sat, 14 May 2005 03:43:35 GMT
header: Server: Apache/1.3.33 (Debian GNU/Linux)
header: Connection: close
header: Content-Type: text/html; charset=iso-8859-1
urllib2を使った例を追加のこと --seko, Sat, 14 May 2005 13:20:02 +0900 reply
デバッグモードでurllib2を使った例を追加のこと。エラーになる。原因不明。
認証タイプを追加すること --seko, Sat, 21 Jan 2006 07:22:31 +0900 reply
ユーザ名とパスワードが必要なタイプのページへのアクセスのサンプルを追加すること