- 网络爬虫
- 一个爬虫源码
- 源码分析
一,网路爬虫
这篇博客简单的实现了一个网路爬虫脚本,所谓网路爬虫就是从网站某一个页面(通常是首页)开始,读取网页的内容,找到在网页中的其它链接地址,然后通过这些链接地址寻找下一个网页,这样一直循环下去,直到把这个网站所有的网页都抓取完为止。
二,一个爬虫源码
下面就是一个简单地网络爬虫程序
#!/usr/bin/env python
#filename:crawle.py
import argparse
import sys
import httplib
import re
processed=[]
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..."%url
if __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链接然后继续搜索,