Screen scraping 2

來源:互聯網
上載者:User

Using HTMLPareser

Using HTMLParser simply means subclassing it, and overriding various event-handling methods such as handle_starttag or handle_data.

Handle_starttag(tag, attrs): When a start tag is found. Attrs is a sequence of (name, value) pairs.

Handle_startendtag(tag, attrs): for empty tags; default handles start and end separately

Handle_endtag(tag): when end tag is found

Handle_data(data): for textual data

Handle_charref(ref): for character references of the form &#ref

Handle_entityref(name): for entity references of the form &name

Handle_decl(decl): for declarations of the form <!...>

Handle_pi(data): for processing instructions

from urllib import urlopenimport refrom HTMLParser import HTMLParserclass Scraper(HTMLParser):    in_h2 = False    in_link = False        def handle_starttag(self, tag, attrs):        attrs = dict(attrs)        if tag == 'h2':            self.in_h2 = True        if tag == 'a' and 'href' in attrs:            self.in_link = True            self.chunks = []            self.url = attrs['href']                def handle_data(self, data):        if self.in_link:            self.chunks.append(data)                def handle_endtag(self, tag):        if tag == 'h2':            self.in_h2 = False        if tag == 'a':            if self.in_h2 and self.in_link:                print '%s (%s)' %(''.join(self.chunks), self.url)            self.in_link = Falsetext = urlopen("http://www.python.org/community/jobs/").read()parser = Scraper()parser.feed(text)parser.close()

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.