关键词: python, 网络爬虫,网站
测试环境:ubuntu 12.04
网络爬虫是一种按照一定的规则,自动的抓取万维网信息的程序或者脚本。
1. 爬虫工作原理
2. http抓取工具 scrapy
百度首页爬虫,并把抓取内容保存到html文件。
程序流程:
- 构建http请求包
- 发送http请求
- 分析网页编码
- 保存网页内容到文件
- 提取网页中特定的某些信息
#!/usr/bin/env python
import urllib2
import sys
import chardet
from bs4 import BeautifulSoup
url="http://www.baidu.com"
req_header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.3.1.2000 Chrome/30.0.1599.101 Safari/537.36',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language':'zh-cn',
'Accept-Encoding':'gzip, deflate'
}
req = urllib2.Request(url)
## Request(url,None,req_header)
resp = urllib2.urlopen(req)
content = resp.read()
info = resp.info()
resp.close()
reload(sys)
infoencode = (chardet.detect(content))['encoding']
print infoencode
charset2 = info.getparam('charset')
print charset2
with open("html1.html","w") as file1:
file1.write(content)
soup = BeautifulSoup(content)
polist=soup.findAll('a')
print len(polist)
注:有些网站有反抓功能,例如南京小百合bbs(http://bbs.nju.edu.cn/)。
3. 其他问题
有效存储(数据库应该怎样安排)
有效判重(网页判重,不想把人民日报和抄袭它的大民日报都爬一遍)
有效信息抽取(比如怎么样抽取出网页上所有路名,“朝阳区奋进路中华道”),搜索引擎通常不需要存储所有的信息,比如图片.
及时更新(预测这个网页多久会更新一次)
大规模网页抓取,分布式
参考资料
http://www.oschina.net/translate/build-website-crawler-based-upon-scrapy
http://www.pythontab.com/html/2013/pythonhexinbiancheng_0814/541.html
http://www.oschina.net/p/cola Cola分布式的爬虫框架
http://www.oschina.net/p/scrapy Scrapy基于Twisted的异步处理框架