webページをゲットする。
>>>import urllib2
>>>urlhandler = urllib2.urlopen("http://www.google.co.jp")
>>>html = urlhandler.read()
一行ずつ読み込む
>>>html = urlhandler.readline()
一行ずつリストに格納
>>>html = urlhandler.readlines()
User-Agentを指定してリクエスト
>>>import urllib2 >>>req = urllib2.Request("http://www.google.co.jp") >>>req.add_header("User-agent", "python") >>>urlhandler = urllib2.urlopen(req)
ヘッダーに色々追加してリクエスト
>>>import urllib2 >>>req = urllib2.Request("http://www.google.co.jp") >>>req.add_header("User-agent", "python") >>>req.add_header("Pragma", "no-cache") >>>urlhandler = urllib2.urlopen(req)
プロクシを指定してリクエスト
>>>import urllib2 >>>req = urllib2.Request("http://www.google.co.jp") >>>req.set_proxy("proxy.example.com:8080", "http") >>>req.add_header("User-agent", "python") >>>req.add_header("Pragma", "no-cache") >>>site = urllib2.urlopen(req)
TCPWatchを使って、リクエストの中身を確認しながらテスト
http://hathawaymix.org/Software/TCPWatch
コマンドラインからTCPWatchを起動する。
c:>tcpwatch.py -p 127.0.0.1:3128
TCPWatchをset_proxyしてリクエストを飛ばす
>>>import urllib2 >>>req = urllib2.Request("http://www.google.co.jp") >>>req.set_proxy("127.0.0.1:3128", "http") >>>req.add_header("User-agent", "python") >>>req.add_header("Pragma", "no-cache") >>>site = urllib2.urlopen(req)
日本語で正規表現を使う
Shift-jisでは値にバックスラッシュ(=0x5c)が含まれる場合がある。(例えば"表"の字)
Pythonではバックスラッシュはエスケープ文字として扱われるので、そのような文字が正規表現のパターンに含まれていると意図しない結果となる。
文字列をいったんunicodeに変換することで、この問題を回避できる。
▼例1
>>> ================================ RESTART ================================ >>> import re >>> string = "表示できますか" >>> print re.sub('表示', "お願い", string) 表示できますか #ちゃんと変換されない >>> patten = "表示" >>> print re.sub(patten.decode("shift-jis"), "お願い",string.decode("shift-jis")) お願いできますか #ちゃんと変換されている
▼例2(yahooから取得したソースを正規表現でサーチする。)
環境:Yahooのページはeuc-jp、Python Shellはshift-jis
対象となる文字データ(ここでは変数html)の文字コードが解っている事を前提。
>>> ================================ RESTART ================================ >>> import urllib2 >>> urlhandler = urllib2.urlopen("http://www.yahoo.co.jp/") >>> html = urlhandler.read() >>> import re >>> pattern = "免責事項" >>> print re.search(pattern.decode("shift-jis"), html.decode("euc_jp")).group() 免責事項
参考:日本語環境でのPython (for Python 2.3 or later)
http://www.python.jp/Zope/articles/japanese/Python4Japanese-2
リンク先では、unicode関数を使っているのだけれど、個人的には文字列のメソッドに統一した方が美しい気がする。
(まぁ、気分の問題)
>>> ================================ RESTART ================================ >>> string = "表示できますか" >>> unicode(string, "shift-jis") u'\u8868\u793a\u3067\u304d\u307e\u3059\u304b' >>> string.encode("shift-jis") '表示できますか'
>>> ================================ RESTART ================================ >>> string = "表示できますか" >>> string.decode("shift-jis") u'\u8868\u793a\u3067\u304d\u307e\u3059\u304b' >>> string.encode("shift-jis") '表示できますか'
参考:2.3.6.1 文字列メソッド
http://www.python.jp/doc/release/lib/string-methods.html#l2h-175