**080:HTMLを処理する**
htmlを処理するためには、まずWEBページからそれをとらなくてはならない。下の例ではurllib,urllib2を使ったが、本質的な違いがよく分からない。多分urllib2の方が高度なことができるのだと思う。
import urllib sock=urllib.urlopen(http://diveintopython.org/) htmlSource = sock.read() sock.close() print htmlSourceimport urllib2 f =urllib2.urlopen(
http://diveintopython.org/) htmlSource = f.read() print htmlSource
htmlもただの文字列であるから、正規表現を使って対処しても構わない。しかし、pythonにはhtmlを取り扱うために、専用のモジュールとして、sgmlibやHTMLParserモジュールがある。sgmlibの方が多分ちょっと高級なのだと思う。
次の例では、WEBページを8192バイトだけ読んで、そこにあるリンクa hrefで始まるものを見つけ出す。(ここではhttpと明示的なものだけをプリントしている)LinksParserクラスではdo_aメソッドだけを定義しているが、スーパークラスは全てのタグに対してこのメソッドをコールバックします。(書いていて意味がわからない)
import sgmllib, urllib, urlparse
class LinksParser(sgmllib.SGMLParser):
def __init__(self):
sgmllib.SGMLParser.__init__(self)
self.seen ={}
def do_a(self, attributes):
for name, value in attributes:
if name == href and value not in self.seen:
self.seen [value] = True
pieces = urlparse.urlparse(value)
if pieces[0] != http : return
print urlparse.urlunparse(pieces)
return
p = LinksParser()
f=urllib.urlopen(http://www.python.org/index.html)
BUFSIZE = 8192
while True:
data = f.read(BUFSIZE)
if not data: break
p.feed(data)
p.close()
http://www.jython.org/ http://www.python.org/pypi http://www.python.org/moin/BeginnersGuide http://www.python.org/moin/ http://www.python.org/moin/PythonBooks http://sourceforge.net/tracker/?group_id=5470&atid=105470 http://sourceforge.net/tracker/?group_id=5470&atid=305470 http://sourceforge.net/cvs/?group_id=5470 以下略