|
1 | 1 | ##爬虫 |
2 | 2 |
|
| 3 | +这一章将会介绍使用一些新的模块(optparse,spider)去完成一个爬虫的web应用。爬虫其实就是一个枚举出一个网站上面的所有链接,以帮助你创建一个网站地图的web应用程序。而使用Python则可以很快的帮助你开发出一个爬虫脚本. |
| 4 | + |
| 5 | +你可以创建一个爬虫脚本通过href标签对请求的响应内容进行解析,并且可以在解析的同时创建一个新的请求,你还可以直接调用spider模块来实现,这样就不需要自己去写那样多的代码了: |
| 6 | + |
| 7 | + |
| 8 | +这里有几个参数你需要去了解一下,不然上面这段脚本是无法成功运行的:"myspider(b=URL.strip(), w=200, d=5, t=5)"这个函数将会返回两个列表:子url链接与路径。你也可以自己修改myspider函数里面的参数: |
| 9 | + |
| 10 | +b — 基本的web url(默认: 无) |
| 11 | +w — 抓取的数量 (默认: 200) |
| 12 | +d — 抓取的深度层级 (默认: 5) |
| 13 | +t — 设置线程数 (默认: 无) |
| 14 | + |
| 15 | +这篇文章主要是先介绍一个web爬虫的入门基础,web资源千变万化。所以未来在博客的其他文章里面再深入的讲述攻击web服务器一些更高级的案例; |
| 16 | + |
| 17 | +图中的python爬虫脚本代码片段: |
| 18 | +``` |
| 19 | +#!/usr/bin/python |
| 20 | +from spider import webspider as myspider |
| 21 | +import sys, optparse |
| 22 | + |
| 23 | +def crawler(URLs): |
| 24 | + for line in open(URLs, 'r'): |
| 25 | + URL = line.strip() |
| 26 | + links = myspider(b=URL.strip(), w=200, d=5, t=5) |
| 27 | + link_count = len(links[0]) |
| 28 | + out = URL+": has a link count of "+str(link_count) |
| 29 | + print "[+] Web Crawl Results for: "+URL |
| 30 | + print out |
| 31 | + for item in links[1]: |
| 32 | + print item |
| 33 | + |
| 34 | +def main(): |
| 35 | +# optparse模块允许你通过参数选项来调用那段代码 |
| 36 | +# 这里我使用 '-r'选项并且内容会保存在URLs变量里面 |
| 37 | +# 当使用-r参数的使用脚本会去读取指定的文件夹 |
| 38 | + parser = optparse.OptionParser(sys.argv[0]+' '+ \ |
| 39 | + '-r <file_with URLs>') |
| 40 | + parser.add_option('-r', dest='URLs', type='string', \ |
| 41 | + help='specify target file with URLs') |
| 42 | + (options, args) = parser.parse_args() |
| 43 | + URLs=options.URLs |
| 44 | + |
| 45 | + if (URLs == None): |
| 46 | + print parser.usage |
| 47 | + sys.exit(0) |
| 48 | + else: |
| 49 | + crawler(URLs) |
| 50 | + |
| 51 | +if __name__ == "__main__": |
| 52 | + main() |
| 53 | +``` |
| 54 | +* [spider模块](https://pypi.python.org/pypi/spider.py/) |
0 commit comments