python核心编程中网络爬虫的例子

  1 #!/usr/bin/env python
  2
  3 import cStringIO                    #
  4 import formatter                    #
  5 from htmllib import HTMLParser         # We use various classes in these modules for parsing HTML.
  6 import httplib                        # We only need an exception from this module
  7 import os                            # This provides various file system functions
  8 import sys                            # We are just using argv for command-line arguments
  9 import urllib                        # We only need the urlretrieve()function for downloading Web pages
 10 import urlparse                        # We use the urlparse()and urljoin()functions for URL manipulation
 11
 12 class Retriever(object):
 13     __slots__ = (‘url‘,‘file‘)
 14
 15     def __init__(self,url):
 16         self.url, self.file = self.get_file(url)
 17
 18     def get_file(self, url, default=‘index.html‘):
 19         ‘Create usable local filename from URL‘
 20         parsed = urlparse.urlparse(url)                     # ParseResult(scheme=‘http‘, netloc=‘www.baidu.com‘, path=‘‘, params=‘‘, query=‘‘, fragment=‘‘)
 21         host = parsed.netloc.split(‘@‘)[-1].split(‘:‘)[0]    # ‘www.baidu.com‘
 22         filepath = ‘%s%s‘ % (host,parsed.path)                # ‘www.baidu.com‘
 23         if not os.path.splitext(parsed.path)[1]:            # ‘‘
 24             filepath = os.path.join(filepath, default)        # ‘www.baidu.com\\index.html‘
 25         linkdir = os.path.dirname(filepath)                    # ‘www.baidu.com‘
 26         if not os.path.isdir(linkdir):                        # False
 27             if os.path.exists(linkdir):                        # False
 28                 os.unlink(linkdir)
 29             os.makedirs(linkdir)                            # make a directory named by link directory on the hard disc
 30         return url, filepath
 31
 32     def download(self):
 33         ‘Download URL to specific name file‘
 34         try:
 35             retval = urllib.urlretrieve(self.url, self.file)
 36         except (IOError, httplib.InvalidURL) as e:
 37             retval = ((‘*** ERROR:bad URL "%s": %s‘ % (self.url,e)),)
 38         return retval
 39
 40     def parse_links(self):
 41         ‘Parse out the links found in downloaded HTML file‘
 42         f = open(self.file, ‘r‘)
 43         data = f.read()
 44         f.close()
 45         parser = HTMLParser(formatter.AbstractFormatter(formatter.DumbWriter(cStringIO.StringIO())))
 46         parser.feed(data)
 47         parser.close()
 48         return parser.anchorlist
 49
 50 class Crawler(object):
 51     count = 0                                                # the number of objects downloaded from the internet
 52
 53     def __init__(self, url):
 54         self.q = [url]                                        # a queue of links to download
 55         self.seen = set()                                    # a set containing all the links that we have seen(downloaded) already
 56         parsed = urlparse.urlparse(url)
 57         host = parsed.netloc.split(‘@‘)[-1].split(‘:‘)[0]
 58         self.dom = ‘.‘.join(host.split(‘.‘)[-2:])            # ‘b.a.i.d.u‘
 59
 60     def get_page(self, url, media=False):
 61         ‘Download page & parse links, add to queue if nec‘
 62         r = Retriever(url)
 63         fname = r.download()[0]                                # ‘www.baidu.com\\index.html‘
 64         if fname[0] == ‘*‘:                                    # ‘w‘
 65             print fname, ‘... skipping parse‘
 66             return
 67         Crawler.count += 1                                    # 1
 68         print ‘\n(‘, Crawler.count, ‘)‘                        # (1)
 69         print ‘URL:‘, url                                    # URL: http://www.baidu.com
 70         print ‘FILE:‘, fname                                # FILE: www.baidu.com\\index.html
 71         self.seen.add(url)                                    # set([‘http://www.baidu.com‘])
 72         ftype = os.path.splitext(fname)[1]                    # ‘.html‘
 73         if ftype not in (‘.htm‘, ‘.html‘):                    # False
 74             return
 75
 76         for link in r.parse_links():
 77             if link.startswith(‘mailto:‘):                    # False
 78                 print ‘... discarded, mailto link‘
 79                 continue
 80             if not media:                                    # False
 81                 ftype = os.path.splitext(link)[1]
 82                 if ftype in (‘.mp3‘,‘.mp4‘,‘.m4v‘,‘.wav‘):
 83                     print ‘... discarded, media file‘
 84                     continue
 85             if not link.startswith(‘http://‘):                # False
 86                 link = urlparse.urljoin(url, link)
 87             print ‘*‘, link,
 88             if link not in self.seen:                        # True
 89                 if self.dom not in link:                    # False
 90                     print ‘... discarded, not in domain‘
 91                 else:
 92                     if link not in self.q:
 93                         self.q.append(link)
 94                         print ‘... new, added to Q‘
 95                     else:
 96                         print ‘... discarded, already in Q‘
 97             else:
 98                 print ‘... discarded, already processed‘
 99
100     def go(self, media=False):
101         ‘Process next page in queue (if any)‘
102         while self.q:
103             url = self.q.pop()
104             self.get_page(url, media)
105
106 def main():
107         if len(sys.argv) > 1:
108             url = sys.argv[1]
109         else:
110             try:
111                 url = raw_input(‘Enter starting URL:‘)
112             except(KeyboardInterrupt, EOFError):
113                 url = ‘‘
114         if not url:
115             return
116         if not url.startswith(‘http://‘) and not url.startswith(‘ftp://‘):
117             url = ‘http://%s/‘ % url
118         robot = Crawler(url)
119         robot.go()
120
121 if __name__ == ‘__main__‘:
122         main()

python核心编程中网络爬虫的例子

时间: 2024-12-17 19:43:10

python核心编程中网络爬虫的例子的相关文章

Python核心编程(网络编程)

1.python socket模块内置方法 2.tcp服务器伪代码 3.tcp客户端伪代码 4.socket模块属性 5.一个简单的tcp客户端和服务端 服务端代码: # encoding:utf-8 from socket import * from time import ctime from datetime import * # 定义tcpServer监听端口号 HOST = '0.0.0.0' PORT = 21567 ADDR = (HOST, PORT) BUFFSIZE=1024

Python核心编程的四大神兽

本文将主要分为4大部分,分别介绍Python核心编程中的迭代器.生成器 .闭包以及装饰器. 生成器 生成器是生成一个值的特殊函数,它具有这样的特点:第一次执行该函数时,先从头按顺序执行,在碰到yield关键字时该函数会暂停执行该函数后续的代码,并且返回一个值:在下一次调用该函数执行时,程序将从上一次暂停的位置继续往下执行. 通过一个例子来理解生成器的执行过程.求1-10的所有整数的立方并将结果打印输出,正常使用列表的实现如下: def lifang_ls(): """求1-1

python核心编程例子3.1

#!/usr/bin/env python # -*- coding:utf-8 -*- 'python核心编程例子3.1:makeTextFile.py -- create text file' import os import sys ls = os.linesep #获取当前平台使用的行终止符.Windows下返回'/r/n',Linux使用'/n'. while True: #按照书的逻辑,此处应该定义个fname,然后循环判断,但是书里没写. fname = raw_input('in

分享《Python核心编程(第3版)》《Python编程入门(第3版)》高清中英文版PDF+源代码

<Python核心编程(第3版)>经典<Python核心编程(第二版)>的全新升级版本,总共分为3部分.第1部分为讲解了Python的一些通用应用,包括正则表达式.网络编程.Internet客户端编程.多线程编程.GUI编程.数据库编程.Microsoft Office编程.扩展Python等内容.第2部分讲解了与Web开发相关的主题,包括Web客户端和服务器.CGI和WSGI相关的Web编程.Django Web框架.云计算.高级Web服务.第3部分则为一个补充/实验章节,包括文

python核心编程--笔记

python核心编程--笔记 的解释器options: 1.1 –d   提供调试输出 1.2 –O   生成优化的字节码(生成.pyo文件) 1.3 –S   不导入site模块以在启动时查找python路径 1.4 –v   冗余输出(导入语句详细追踪) 1.5 –m mod 将一个模块以脚本形式运行 1.6 –Q opt 除法选项(参阅文档) 1.7 –c cmd 运行以命令行字符串心事提交的python脚本 1.8 file   以给定的文件运行python脚本 2 _在解释器中表示最后

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

生成器 生成器是生成一个值的特殊函数,它具有这样的特点:第一次执行该函数时,先从头按顺序执行,在碰到yield关键字时该函数会暂停执行该函数后续的代码,并且返回一个值:在下一次调用该函数执行时,程序将从上一次暂停的位置继续往下执行. 通过一个例子来理解生成器的执行过程.求1-10的所有整数的立方并将结果打印输出,正常使用列表的实现如下: 输出结果如下: 当数据量很少时,可以很快得到结果.但是如果范围扩大到10000甚至是100000000,就会发现程序执行时间会变长,变卡,甚至有可能会因超出内存

Python核心编程 第3版 中文版pdf

[下载地址] <Python核心编程(第3版)>是经典畅销图书<Python核心编程(第二版)>的全新升级版本,总共分为3部分.第1部分为讲解了Python的一些通用应用,包括正则表达式.网络编程.Internet客户端编程.多线程编程.GUI编程.数据库编程.Microsoft Office编程.扩展Python等内容.第2部分讲解了与Web开发相关的主题,包括Web客户端和服务器.CGI和WSGI相关的Web编程.Django Web框架.云计算.高级Web服务.第3部分则为一

《Python核心编程》 第五章 数字 - 课后习题

课后习题  5-1 整形. 讲讲 Python 普通整型和长整型的区别. 答:普通整型是绝大多数现代系统都能识别的. Python的长整型类型能表达的数值仅仅与你机器支持的(虚拟)内存大小有关. 5-2 运算符 (a) 写一个函数,计算并返回两个数的乘积 (b) 写一段代码调用这个函数,并显示它的结果 答: def pro(a,b): p = a*b return p a = int(raw_input("a=")) b = int(raw_input("b="))

Python黑客编程3网络数据监听和过滤

Python黑客编程3网络数据监听和过滤 课程的实验环境如下: ?      操作系统:kali Linux 2.0 ?      编程工具:Wing IDE ?      Python版本:2.7.9 ?      涉及到的主要python模块:pypcap,dpkt,scapy,scapy-http 涉及到的几个python网络抓包和分析的模块,dpkt和scapy在kali linux 2.0 中默认已经被安装,如果你的系统中没有需要手动安装一下,下面是软件包安装的简单说明. 在kali下