python网路爬虫
来源:互联网 发布:linux ftp服务安装 编辑:程序博客网 时间:2024/05/16 18:35
- 网络爬虫
- 一个爬虫源码
- 源码分析
一,网路爬虫
这篇博客简单的实现了一个网路爬虫脚本,所谓网路爬虫就是从网站某一个页面(通常是首页)开始,读取网页的内容,找到在网页中的其它链接地址,然后通过这些链接地址寻找下一个网页,这样一直循环下去,直到把这个网站所有的网页都抓取完为止。
二,一个爬虫源码
下面就是一个简单地网络爬虫程序
#!/usr/bin/env python#filename:crawle.pyimport argparseimport sysimport httplibimport reprocessed=[]def search_links(url,depth,search): url_is_processed=(url in processed) if(url.startwith("http://") and (not url_is processed)): processed.append(url) url=host=url.replace("http://","",1) path='/' urlparts=url.split("/") if(len(urlparts)>1): host=urlparts[0] path=url.replace(host,"",1) print "Crawling URL path:%s%s"%(host,path) conn =httplib.HTTPConnection(host) req=conn.request("GET",path) result=conn.getresponse() contents=result.read() all_links=re.findall('href="(.*?)"',contents) if(search in contents): print "Found"+search+"at"+url print"==> %s: processing %s links"\ %(str(depth),str(len(all_links))) for href in all_links: if(href.startwith("/")): href="http://"+host+href if(depth>0): search_links(href,depth-1,search) else: print "Skipping link: %s..."%urlif __name__=="__main__": parser=pargparse.ArgumentParser(\ description="Webpage link crawler") parser.add_argument("--url",action="store",\ dest="url",require=True) parser.add_argument("--query",action="store",\ dest="query",require=True) parser.add_argument("--depth",action="store",\ dest="depth",default=2) given_args=parser.parse.args() try: search_links(given_args.url,given_args.depth, given_args.query) except KeyboardInterrupt: print "Aborting search by user request."#use: ./crawle --url="http://python.org" --query="python" --depth=3#note:这个命令的意思是,从http://python.org爬去寻找关键字#python搜索深度是3
三,源码分析
在这份源码里面
1,argparse模块用于定义命令行参数的解析,这个模块经常用于自定义命令,实现一些小的功能,比如在这份源码里面定义了三个命令分别是:
“–url”,”–query”,”–depth”。
这三个命令分别用于定义搜索的url以及关键字,以及搜索深度
2,re模块主要用于正则分析爬去到的内容,从里面找到新的url
3,这份脚本里面的函数search_links()是一个递归函数,结束条件是depth=0,里面关键的一句是:
all_links=re.findall(‘href=”(.*?)”’,contents),
。。。。。
for href in all_links:
if(href.startwith(“/”)):
href=”http://”+host+href
if(depth>0):
search_links(href,depth-1,search)
这个会从读到的内容里面寻找所有新的url链接然后继续搜索,
0 0
- python网路爬虫
- iOS程序员如何使用python写网路爬虫
- iOS程序员如何使用Python写网路爬虫
- iOS程序员如何使用python写网路爬虫
- iOS程序员如何使用Python写网路爬虫
- 网路爬虫--url索引
- 第一个网路爬虫
- 网路基础(python)
- python爬虫-->爬虫基础
- [爬虫] Python爬虫技巧
- 使用Python脚本创建OVS交换机网路
- Python爬虫
- python 爬虫
- python 爬虫
- python 爬虫
- python爬虫
- Python爬虫
- Python爬虫
- Java基础day13 StringBuffer类
- 简单而漂亮的登录页面。。。
- HDU 1062 Text Reverse(水题)
- vector::clear()和vecotr::pop_back()对内存处理的不同 http://blog.csdn.net/vieri_ch/article/details/1191390
- java初步学习之队列
- python网路爬虫
- 默然说话20160304
- Android获取Manifest中<meta-data>元素的值
- 偏颇之论——志不同道不合,节约对方的时间,就是最大的尊重。
- 数组名是一个指针常量吗?
- Hust oj 1812 小乐乐想出门(基础dp)
- C语言——源码、反码、补码
- java集合面试题
- 寒假刷题-动态规划