博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Screen scraping 2
阅读量:7053 次
发布时间:2019-06-28

本文共 1584 字,大约阅读时间需要 5 分钟。

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()

 

转载于:https://www.cnblogs.com/bluescorpio/archive/2012/05/22/2513950.html

你可能感兴趣的文章
IOS 关于上传图片裁剪以及压缩,确保高清
查看>>
HDU - 6115 Factory (LCA 倍增)
查看>>
unity客户端与c++服务器之间的简单通讯_1
查看>>
Python_反射
查看>>
Codeforces-963 D Frequency of String
查看>>
MyBatis-mybatis全局映射文件解析
查看>>
WebApi 跨域解决方案 --CORS
查看>>
MySQL系列详解五: xtrabackup实现完全备份及增量备份详解-技术流ken
查看>>
单独编译Android源代码中的模块
查看>>
manjaro安装mysql5.7
查看>>
记录零散的知识点
查看>>
H5上传图片并使用canvas制作海报
查看>>
springmvc学习笔记
查看>>
LRU算法的设计
查看>>
Java util包中常用的类和方法
查看>>
[R] 之 管理工作空间函数
查看>>
将windows目录共享到linux
查看>>
计算机是如何启动的
查看>>
Python的raw_input语句包含中文,在Windows环境CMD中显示乱码的解决方法
查看>>
HIbernate学习笔记3 之 缓存和 对象的三种状态
查看>>