#!/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核心编程中网络爬虫的例子的更多相关文章

  1. python核心编程中的对象值比较VS对象身份比较(转载)

    转载地址: https://blog.csdn.net/Mluka/article/details/51076786 在python核心编程第四章中,P69在优化下面这段代码时提出了:对象值比较VS对 ...

  2. Python核心编程(网络编程)

    1.python socket模块内置方法 2.tcp服务器伪代码 3.tcp客户端伪代码 4.socket模块属性 5.一个简单的tcp客户端和服务端 服务端代码: # encoding:utf-8 ...

  3. Python核心编程-描述符

    python中,什么描述符.描述符就是实现了"__get__"."__set__"或"__delete__" 方法中至少一个的对象.什么是非 ...

  4. python核心编程第二版笔记

    python核心编程第二版笔记由网友提供:open168 python核心编程--笔记(很详细,建议收藏) 解释器options:1.1 –d   提供调试输出1.2 –O   生成优化的字节码(生成 ...

  5. python核心编程--笔记

    python核心编程--笔记 的解释器options: 1.1 –d   提供调试输出 1.2 –O   生成优化的字节码(生成.pyo文件) 1.3 –S   不导入site模块以在启动时查找pyt ...

  6. Python核心编程第二版(中文).pdf 目录整理

    python核心编程目录 Chapter1:欢迎来到python世界!-页码:7 1.1什么是python 1.2起源  :罗萨姆1989底创建python 1.3特点 1.3.1高级 1.3.2面向 ...

  7. Python核心编程的四大神兽:迭代器、生成器、闭包以及装饰器

      生成器 生成器是生成一个值的特殊函数,它具有这样的特点:第一次执行该函数时,先从头按顺序执行,在碰到yield关键字时该函数会暂停执行该函数后续的代码,并且返回一个值:在下一次调用该函数执行时,程 ...

  8. python核心编程--笔记(不定时跟新)(转)

    的解释器options: 1.1 –d   提供调试输出 1.2 –O   生成优化的字节码(生成.pyo文件) 1.3 –S   不导入site模块以在启动时查找python路径 1.4 –v   ...

  9. python核心编程笔记(转)

    解释器options: 1.1 –d   提供调试输出 1.2 –O   生成优化的字节码(生成.pyo文件) 1.3 –S   不导入site模块以在启动时查找python路径 1.4 –v   冗 ...

随机推荐

  1. git——合并分支

    A将自己的本地代码提交到远程A分支,此时master主干上有B新提交的代码,如果此时A把自己的代码merge到主干,会有冲突,那怎么办? 1.A将自己的代码提交到自己的A分支 2.git fetch ...

  2. C++ 调用Python3

    作为一种胶水语言,Python 能够很容易地调用 C . C++ 等语言,也能够通过其他语言调用 Python 的模块. Python 提供了 C++ 库,使得开发者能很方便地从 C++ 程序中调用 ...

  3. 深度学习(五)基于tensorflow实现简单卷积神经网络Lenet5

    原文作者:aircraft 原文地址:https://www.cnblogs.com/DOMLX/p/8954892.html 参考博客:https://blog.csdn.net/u01287127 ...

  4. TOJ 2926 Series

    Description An arithmetic series consists of a sequence of terms such that each term minus its immed ...

  5. 触发Full GC的时机

    由于Full GC的耗时是Minor GC的十倍左右,所以Full GC的频率设计得比Minor GC低得多.现总结一下触发Full GC的情况. 在那些实现了CMS的比较新的虚拟机中,如果配置了-X ...

  6. Red–black tree ---reference wiki

    source address:http://en.wikipedia.org/wiki/Red%E2%80%93black_tree A red–black tree is a type of sel ...

  7. FZU 2207 ——以撒的结合——————【LCA + 记录祖先】

    Problem 2207 以撒的结合 Accept: 47    Submit: 161Time Limit: 1000 mSec    Memory Limit : 32768 KB  Proble ...

  8. 【linux相识相知】VIM编辑器

    Vim是一个类似Vi的著名的功能强大.高度可定制的文本编辑器,在Vi的基础上改进和增加了许多的功能,VIM是自由软件,今天我们就来讲讲VIM的使用方法. 本文是基于centos7上的vim编辑器演示的 ...

  9. bzoj 4543: [POI2014]Hotel加强版

    Description 给出一棵树求三元组 \((x,y,z)\,,x<y<z\) 满足三个点两两之间距离相等,求三元组的数量 Solution 考虑暴力 \(DP\) 设 \(f[i][ ...

  10. 【Shell】shell截取字符串方式(cut、awk、sed命令)

    1.cut -b :以字节为单位进行分割.这些字节位置将忽略多字节字符边界,除非也指定了 -n 标志.-c :以字符为单位进行分割. -d:自定义分隔符,默认为制表符. -f:与-d一起使用,指定显示 ...