python核心编程中网络爬虫的例子
#!/usr/bin/env python import cStringIO #
import formatter #
from htmllib import HTMLParser # We use various classes in these modules for parsing HTML.
import httplib # We only need an exception from this module
import os # This provides various file system functions
import sys # We are just using argv for command-line arguments
import urllib # We only need the urlretrieve()function for downloading Web pages
import urlparse # We use the urlparse()and urljoin()functions for URL manipulation class Retriever(object):
__slots__ = ('url','file') def __init__(self,url):
self.url, self.file = self.get_file(url) def get_file(self, url, default='index.html'):
'Create usable local filename from URL'
parsed = urlparse.urlparse(url) # ParseResult(scheme='http', netloc='www.baidu.com', path='', params='', query='', fragment='')
host = parsed.netloc.split('@')[-1].split(':')[0] # 'www.baidu.com'
filepath = '%s%s' % (host,parsed.path) # 'www.baidu.com'
if not os.path.splitext(parsed.path)[1]: # ''
filepath = os.path.join(filepath, default) # 'www.baidu.com\\index.html'
linkdir = os.path.dirname(filepath) # 'www.baidu.com'
if not os.path.isdir(linkdir): # False
if os.path.exists(linkdir): # False
os.unlink(linkdir)
os.makedirs(linkdir) # make a directory named by link directory on the hard disc
return url, filepath def download(self):
'Download URL to specific name file'
try:
retval = urllib.urlretrieve(self.url, self.file)
except (IOError, httplib.InvalidURL) as e:
retval = (('*** ERROR:bad URL "%s": %s' % (self.url,e)),)
return retval def parse_links(self):
'Parse out the links found in downloaded HTML file'
f = open(self.file, 'r')
data = f.read()
f.close()
parser = HTMLParser(formatter.AbstractFormatter(formatter.DumbWriter(cStringIO.StringIO())))
parser.feed(data)
parser.close()
return parser.anchorlist class Crawler(object):
count = 0 # the number of objects downloaded from the internet def __init__(self, url):
self.q = [url] # a queue of links to download
self.seen = set() # a set containing all the links that we have seen(downloaded) already
parsed = urlparse.urlparse(url)
host = parsed.netloc.split('@')[-1].split(':')[0]
self.dom = '.'.join(host.split('.')[-2:]) # 'b.a.i.d.u' def get_page(self, url, media=False):
'Download page & parse links, add to queue if nec'
r = Retriever(url)
fname = r.download()[0] # 'www.baidu.com\\index.html'
if fname[0] == '*': # 'w'
print fname, '... skipping parse'
return
Crawler.count += 1 #
print '\n(', Crawler.count, ')' # (1)
print 'URL:', url # URL: http://www.baidu.com
print 'FILE:', fname # FILE: www.baidu.com\\index.html
self.seen.add(url) # set(['http://www.baidu.com'])
ftype = os.path.splitext(fname)[1] # '.html'
if ftype not in ('.htm', '.html'): # False
return for link in r.parse_links():
if link.startswith('mailto:'): # False
print '... discarded, mailto link'
continue
if not media: # False
ftype = os.path.splitext(link)[1]
if ftype in ('.mp3','.mp4','.m4v','.wav'):
print '... discarded, media file'
continue
if not link.startswith('http://'): # False
link = urlparse.urljoin(url, link)
print '*', link,
if link not in self.seen: # True
if self.dom not in link: # False
print '... discarded, not in domain'
else:
if link not in self.q:
self.q.append(link)
print '... new, added to Q'
else:
print '... discarded, already in Q'
else:
print '... discarded, already processed' def go(self, media=False):
'Process next page in queue (if any)'
while self.q:
url = self.q.pop()
self.get_page(url, media) def main():
if len(sys.argv) > 1:
url = sys.argv[1]
else:
try:
url = raw_input('Enter starting URL:')
except(KeyboardInterrupt, EOFError):
url = ''
if not url:
return
if not url.startswith('http://') and not url.startswith('ftp://'):
url = 'http://%s/' % url
robot = Crawler(url)
robot.go() if __name__ == '__main__':
main()
python核心编程中网络爬虫的例子的更多相关文章
- python核心编程中的对象值比较VS对象身份比较(转载)
转载地址: https://blog.csdn.net/Mluka/article/details/51076786 在python核心编程第四章中,P69在优化下面这段代码时提出了:对象值比较VS对 ...
- Python核心编程(网络编程)
1.python socket模块内置方法 2.tcp服务器伪代码 3.tcp客户端伪代码 4.socket模块属性 5.一个简单的tcp客户端和服务端 服务端代码: # encoding:utf-8 ...
- Python核心编程-描述符
python中,什么描述符.描述符就是实现了"__get__"."__set__"或"__delete__" 方法中至少一个的对象.什么是非 ...
- python核心编程第二版笔记
python核心编程第二版笔记由网友提供:open168 python核心编程--笔记(很详细,建议收藏) 解释器options:1.1 –d 提供调试输出1.2 –O 生成优化的字节码(生成 ...
- python核心编程--笔记
python核心编程--笔记 的解释器options: 1.1 –d 提供调试输出 1.2 –O 生成优化的字节码(生成.pyo文件) 1.3 –S 不导入site模块以在启动时查找pyt ...
- Python核心编程第二版(中文).pdf 目录整理
python核心编程目录 Chapter1:欢迎来到python世界!-页码:7 1.1什么是python 1.2起源 :罗萨姆1989底创建python 1.3特点 1.3.1高级 1.3.2面向 ...
- Python核心编程的四大神兽:迭代器、生成器、闭包以及装饰器
生成器 生成器是生成一个值的特殊函数,它具有这样的特点:第一次执行该函数时,先从头按顺序执行,在碰到yield关键字时该函数会暂停执行该函数后续的代码,并且返回一个值:在下一次调用该函数执行时,程 ...
- python核心编程--笔记(不定时跟新)(转)
的解释器options: 1.1 –d 提供调试输出 1.2 –O 生成优化的字节码(生成.pyo文件) 1.3 –S 不导入site模块以在启动时查找python路径 1.4 –v ...
- python核心编程笔记(转)
解释器options: 1.1 –d 提供调试输出 1.2 –O 生成优化的字节码(生成.pyo文件) 1.3 –S 不导入site模块以在启动时查找python路径 1.4 –v 冗 ...
随机推荐
- hdu2588 GCD
GCD Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submiss ...
- PIE SDK图层树伙伴控件示例
1. 功能简介 TocControl控件的主要作用是显示当前加载的图层有哪些.采用什么样的符号等,目的是使用户对当前加载的数据和结构有一个总体的把握.与之相关联的伙伴控件有MapControl,Pa ...
- 启动Kafka
启动zookeeper 使用命令查看zookeeper是否启动成功: 启动kafka Brokerr 使用命令查看kafka Broker是否启动更成功 在kafka中创建topic 'test' b ...
- 算法市场 Algorithmia
算法市场 官网:(需要***,fan qiang,不然可能访问不了或登录不了) https://algorithmia.com/ 官方的例子: 我不用 curl 发请求,把 curl 命令粘贴给你们用 ...
- 轻量级ORM框架:Dapper中的一些复杂操作和inner join应该注意的坑
上一篇博文中我们快速的介绍了dapper的一些基本CURD操作,也是我们manipulate db不可或缺的最小单元,这一篇我们介绍下相对复杂 一点的操作,源码分析暂时就不在这里介绍了. 一:tabl ...
- Kibana修改Time日志格式
选择左侧management 打开Advanced Settings 编辑:dateFormat,默认格式是:MMMM Do YYYY, HH:mm:ss.SSS,修改为:YYYY-MM-DD HH: ...
- CentOS初试
由于实在是对ubuntu不太感冒,加上买的鸟哥又是拿CentOS做的例子,所以我就把ubuntu换成了CentOS6.5.依旧win7,CentOS 双系统,具体过程参照http://www.cnbl ...
- Java for循环的几种用法分析
J2SE 1.5提供了另一种形式的for循环.借助这种形式的for循环,可以用更简单地方式来遍历数组和Collection等类型的对象.本文介绍使用这种循环的具体方式,说明如何自行定义能被这样遍历的类 ...
- HashMap的结构算法及代码分析
HashMap算是日常开发中最长用的类之一了,我们应该了解它的结构跟算法: 参考文章: http://blog.csdn.net/vking_wang/article/details/14166593 ...
- unity接入讯飞教程
[全流程]<按照这个流程做即可,有不懂得可以看下面的2个><这个是<eclipse>> http://blog.csdn.net/qq_15267341/artic ...