
python實現(xiàn)簡易采集爬蟲_python實現(xiàn)爬蟲_網(wǎng)絡爬蟲 python
#!/usr/bin/python
#-*-coding:utf-8-*-
# 簡易采集爬蟲
# 1.采集Yahoo!Answers,parseData函數(shù)修改一下,可以采集任何網(wǎng)站
# 2.需要sqlite3或者pysqlite支持
# 3.可以在DreamHost.com空間上面運行
# 4.可以修改User-Agent冒充搜索引擎蜘蛛
# 5.可以設置暫停的時間,控制采集速度
# 6.采集Yahoo會被封IP數(shù)小時,所以這個采集用處不大
# Author: Lukin<mylukin@gmail.com>
# Date : 2008-09-25
# 導入采集需要用到的模塊
import re, sys, time
import httplib, os.path as osp
from urlparse import urlparse
# 使用sqite數(shù)據(jù)庫,為了兼容DreamHost.com的空間,只能這么寫了
try :
import sqlite3 as sqlite
except ImportError:
from pysqlite2 import dbapi2 as sqlite
# 采集速度控制,單位秒
sleep = 0
# 數(shù)據(jù)庫路徑
dbname = ‘./database.db’
# 設置提交的header頭
headers = {“Accept”: “*/*”,”Referer”: “http://answers.yahoo.com/”,”User-Agent”: “Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)”}
# 連接服務器
dl = httplib.HTTPConnection(‘a(chǎn)nswers.yahoo.com’)
# 連接數(shù)據(jù)庫
conn = sqlite.connect(osp.abspath(dbname))
# 創(chuàng)建數(shù)據(jù)庫
def createDatabase():
global conn,dbname;
if osp.isfile(osp.abspath(dbname)) : return
c = conn.cursor()
# 創(chuàng)建url列表存放表
c.execute(”’CREATE TABLE IF NOT EXISTS [collect]([cid] INTEGER PRIMARY KEY,[curl] TEXT,[state] INTEGER DEFAULT ‘0’,UNIQUE([curl]));”’)
c.execute(”’CREATE INDEX IF NOT EXISTS [collect_idx_state] ON [collect]([state]);”’)
# 創(chuàng)建分類表
c.execute(”’CREATE TABLE IF NOT EXISTS [sorts]([sortid] INTEGER PRIMARY KEY,[sortname] TEXT,[sortpath] TEXT,[sortfoot] INTEGER DEFAULT ‘0’,[sortnum] INTEGER DEFAULT ‘0’,UNIQUE([sortpath]));”’)
c.execute(”’CREATE INDEX IF NOT EXISTS [sorts_idx_sortname] ON [sorts]([sortname]);”’)
c.execute(”’CREATE INDEX IF NOT EXISTS [sorts_idx_sortfoot] ON [sorts]([sortfoot]);”’)
# 創(chuàng)建文章表
c.execute(”’CREATE TABLE IF NOT EXISTS [article]([aid] INTEGER PRIMARY KEY,[sortid] INTEGER DEFAULT ‘0’,[hits] INTEGER DEFAULT ‘0’,[title] TEXT,[path] TEXT,[question] TEXT,[banswer] TEXT,[oanswer] TEXT,UNIQUE([path]));”’)
c.execute(”’CREATE INDEX IF NOT EXISTS [article_idx_sortid] ON [article]([sortid]);”’)
# 事物提交
conn.commit()
c.close()
# 執(zhí)行采集
def collect(url=”http://answers.yahoo.com/”):
global dl,error,headers; R = 0
print “GET:”,url
urls = urlparse(url); path = urls[2];
if urls[4]!=” : path += ‘?’ + urls[4]
dl.request(method=”GET”, url=path, headers=headers); rs = dl.getresponse()
if rs.status==200 :
R = parseData(rs.read(),url);
else :
print “3 seconds, try again …”; time.sleep(3)
dl.request(method=”GET”, url=path, headers=headers); rs = dl.getresponse()
if rs.status==200 :
R = parseData(rs.read(),url);
else :
print “3 seconds, try again …”; time.sleep(3)
dl.request(method=”GET”, url=path, headers=headers); rs = dl.getresponse()
if rs.status==200 :
R = parseData(rs.read(),url);
else :
print “Continue to collect …”
R = 3
# 更新記錄
updateOneUrl(url,R)
# 返回結果
return R
# 處理采集到的數(shù)據(jù)
def parseData(html,url):
global dl,conn; R = 2;
c = conn.cursor()
# 格式化html代碼
format = formatURL(clearBlank(html),url)
# 取出所有的連接
urls = re.findall(r”'(<a[^>]*?href=”([^”]+)”[^>]*?>)|(<a[^>]*?href='([^’]+)'[^>]*?>)”’,format,re.I)
if urls != None :
i = 0
# 循環(huán)所有的連接
for regs in urls :
# 得到一個單一的url
sUrl = en2chr(regs[1].strip())
# 判斷url是否符合規(guī)則,符合,則插入數(shù)據(jù)庫
if re.search(‘http(.*?)/(dir|question)/index(.*?)’,sUrl,re.I) != None :
if re.search(‘http(.*?)/dir/index(.*?)’,sUrl,re.I) != None:
if sUrl.find(‘link=list’) == -1 and sUrl.find(‘link=over’) == -1 :
sUrl+= ‘&link=over’
else:
sUrl = sUrl.replace(‘link=list’,’link=over’)
if sUrl[-11:]==’link=mailto’ : continue
try :
c.execute(‘INSERT INTO [collect]([curl])VALUES(?);’,(sUrl,))
i = i + 1
except sqlite.IntegrityError :
pass
if i>0 : print “Message: %d get a new URL.” % (i,)
# 截取數(shù)據(jù)
if re.search(‘http(.*)/question/index(.*)’,url,re.I) != None :
sortfoot = 0
# 自動創(chuàng)建分類和分類關系
guide = sect(format,'<ol id=”yan-breadcrumbs”>’,'</ol>’,'(<li>(.*?)Home(.*?)</li>)’)
aGuide = re.findall(‘<a[^>]*href=”[^”]*”[^>]*>(.*?)</a>’,guide,re.I)
if aGuide != None :
sortname = “”
for sortname in aGuide :
sortname = sortname.strip()
sortpath = en2path(sortname)
# 查詢分類是否存在
c.execute(‘SELECT [sortid],[sortname] FROM [sorts] WHERE [sortpath]=? LIMIT 0,1;’,(sortpath,))
row = c.fetchone();
# 分類不存在,添加分類
if row==None :
c.execute(‘INSERT INTO [sorts]([sortname],[sortpath],[sortfoot])VALUES(?,?,?);’,(sortname,sortpath,sortfoot))
sortfoot = c.lastrowid
else:
sortfoot = row[0]
# 標題
title = sect(format,'<h1 class=”subject”>’,'</h1>’)
# 最佳答案
BestAnswer = sect(format,'(<h2><span>Best Answer</span>(.*?)</h2>(.*?)<div class=”content”>)’,'(</div>)’)
# 最佳答案不存在,則不采集
if BestAnswer != None :
# 文章路徑
path = en2path(sortname + ‘-‘ + title.strip())
# 問題
adddata = sect(format,'<div class=”additional-details”>’,'</div>’)
content = sect(format,'(<h1 class=”subject”>(.*?)<div class=”content”>)’,'(</div>)’)
if adddata != None : content += ‘<br/>’ + adddata
# 其他回答
OtherAnswer = ”
for regs in re.findall(‘<div class=”qa-container”>(.+?)<div class=”utils-container”>’,format):
if regs.find(‘<h2>’) == -1 and regs.find(‘</h2>’) == -1 :
a1 = sect(regs,'<div class=”content”>’,'</div>’)
a2 = sect(regs,'<div class=”reference”>’,'</div>’)
OtherAnswer+= ‘<div class=”oAnswer”>’ + a1
if a2 != None : OtherAnswer+= ‘<div class=”reference”>’ + a2 + ‘</div>’
OtherAnswer+= ‘</div>’
# 判斷采集成功
if title != None and content != None :
# 將數(shù)據(jù)寫入到數(shù)據(jù)
try :
c.execute(‘INSERT INTO [article]([sortid],[title],[path],[question],[banswer],[oanswer])VALUES(?,?,?,?,?,?);’,(sortfoot,title,path,content,BestAnswer,OtherAnswer))
print “Message:%s.html” % (path,)
R = 1
except sqlite.IntegrityError :
pass
# 提交寫入數(shù)據(jù)庫
conn.commit(); c.close()
return R
# 取得一條URL
def getOneUrl():
global conn; c = conn.cursor()
c.execute(‘SELECT [curl] FROM [collect] WHERE [state] IN(0,3) LIMIT 0,1;’)
row = c.fetchone(); c.close()
if row==None : return “”
return row[0].encode(‘utf-8’)
# 更新一條記錄的狀態(tài)
def updateOneUrl(url,state):
global conn; c = conn.cursor()
c.execute(‘UPDATE [collect] SET [state]=? WHERE [curl]=?;’,(state,url))
conn.commit(); c.close()
# 清除html代碼里的多余空格
def clearBlank(html):
if len(html) == 0 : return ”
html = re.sub(‘\r|\n|\t’,”,html)
while html.find(” “)!=-1 or html.find(‘ ’)!=-1 :
html = html.replace(‘ ’,’ ‘).replace(‘ ‘,’ ‘)
return html
# 格式化url
def formatURL(html,url):
urls = re.findall(”'(<a[^>]*?href=”([^”]+)”[^>]*?>)|(<a[^>]*?href='([^’]+)'[^>]*?>)”’,html,re.I)
if urls == None : return html
for regs in urls :
html = html.replace(regs[0],matchURL(regs[0],url))
return html
# 格式化單個url
def matchURL(tag,url):
urls = re.findall(”'(.*)(src|href)=(.+?)( |/>|>).*|(.*)url\(([^\)]+)\)”’,tag,re.I)
if urls == None :
return tag
else :
if urls[0][5] == ” :
urlQuote = urls[0][2]
else:
urlQuote = urls[0][5]
if len(urlQuote) > 0 :
cUrl = re.sub(”'[‘”]”’,”,urlQuote)
else :
return tag
urls = urlparse(url); scheme = urls[0];
if scheme!=” : scheme+=’://’
host = urls[1]; host = scheme + host
if len(host)==0 : return tag
path = osp.dirname(urls[2]);
if path==’/’ : path = ”;
if cUrl.find(“#”)!=-1 : cUrl = cUrl[:cUrl.find(“#”)]
# 判斷類型
if re.search(”’^(http|https|ftp):(//|\\\\)(([\w/\\\+\-~`@:%])+\.)+([\w/\\\.\=\?\+\-~`@’:!%#]|(&)|&)+”’,cUrl,re.I) != None :
# http開頭的url類型要跳過
return tag
elif cUrl[:1] == ‘/’ :
# 絕對路徑
cUrl = host + cUrl
elif cUrl[:3]==’../’ :
# 相對路徑
while cUrl[:3]==’../’ :
cUrl = cUrl[3:]
if len(path) > 0 :
path = osp.dirname(path)
elif cUrl[:2]==’./’ :
cUrl = host + path + cUrl[1:]
elif cUrl.lower()[:7]==’mailto:’ or cUrl.lower()[:11]==’javascript:’ :
return tag
else :
cUrl = host + path + ‘/’ + cUrl
R = tag.replace(urlQuote,'”‘ + cUrl + ‘”‘)
return R
# html代碼截取函數(shù)
def sect(html,start,end,cls=”):
if len(html)==0 : return ;
# 正則表達式截取
if start[:1]==chr(40) and start[-1:]==chr(41) and end[:1]==chr(40) and end[-1:]==chr(41) :
reHTML = re.search(start + ‘(.*?)’ + end,html,re.I)
if reHTML == None : return
reHTML = reHTML.group()
intStart = re.search(start,reHTML,re.I).end()
intEnd = re.search(end,reHTML,re.I).start()
R = reHTML[intStart:intEnd]
# 字符串截取
else :
# 取得開始字符串的位置
intStart = html.lower().find(start.lower())
# 如果搜索不到開始字符串,則直接返回空
if intStart == -1 : return
# 取得結束字符串的位置
intEnd = html[intStart+len(start):].lower().find(end.lower())
# 如果搜索不到結束字符串,也返回為空
if intEnd == -1 : return
# 開始和結束字符串都有了,可以開始截取了
R = html[intStart+len(start):intStart+intEnd+len(start)]
# 清理內(nèi)容
if cls != ” :
R = clear(R,cls)
# 返回截取的字符
return R
# 正則清除
def clear(html,regexs):
if regexs == ” : return html
for regex in regexs.split(chr(10)):
regex = regex.strip()
if regex != ” :
if regex[:1]==chr(40) and regex[-1:]==chr(41):
html = re.sub(regex,”,html,re.I|re.S)
else :
html = html.replace(regex,”)
return html
# 格式化為路徑
def en2path(enStr):
return re.sub(‘[\W]+’,’-‘,en2chr(enStr),re.I|re.U).strip(‘-‘)
# 替換實體為正常字符
def en2chr(enStr):
return enStr.replace(‘&’,’&’)
# ————————————- 開始執(zhí)行程序 ——————————————-
# 首先創(chuàng)建數(shù)據(jù)庫
createDatabase()
# 開始采集
loops = 0
while True:
if loops>0 :
url = getOneUrl()
if url == “” :
loops = 0
else :
loops = collect(url)
else :
loops = collect()
# 暫停
time.sleep(sleep)
if loops==0 : break
# 關閉HTTP連接
dl.close()
# 退出程序
sys.exit()
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
DSGE 模型中的 Et:理性預期算子的內(nèi)涵、作用與應用解析 動態(tài)隨機一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結構數(shù)據(jù)特征價值的專業(yè)核心 表結構數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲的結構化數(shù)據(jù),如數(shù)據(jù)庫表、Excel 表、 ...
2025-09-17Excel 導入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實戰(zhàn)應用 在用 Python(如 pandas 庫)處理 Excel 數(shù)據(jù)時,“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗與 t 檢驗:差異、適用場景與實踐應用 在數(shù)據(jù)分析與統(tǒng)計學領域,假設檢驗是驗證研究假設、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結構數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結構數(shù)據(jù)(以 “行 - 列” 存儲的結構化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計劃中 rows 數(shù)量的準確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對象的 text 與 content:區(qū)別、場景與實踐指南 在 Python 進行 HTTP 網(wǎng)絡請求開發(fā)時(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結構數(shù)據(jù)價值的核心操盤手 表格結構數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫表)是企業(yè)最基礎、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請求工具對比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長浮點數(shù)據(jù)的科學計數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長浮點數(shù)據(jù)時的科學計數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務數(shù)據(jù)分析步驟的落地者與價值優(yōu)化者 業(yè)務數(shù)據(jù)分析是企業(yè)解決日常運營問題、提升執(zhí)行效率的核心手段,其價值 ...
2025-09-12用 SQL 驗證業(yè)務邏輯:從規(guī)則拆解到數(shù)據(jù)把關的實戰(zhàn)指南 在業(yè)務系統(tǒng)落地過程中,“業(yè)務邏輯” 是連接 “需求設計” 與 “用戶體驗 ...
2025-09-11塔吉特百貨孕婦營銷案例:數(shù)據(jù)驅(qū)動下的精準零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當下,精準營銷成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務數(shù)據(jù)分析:概念辨析與協(xié)同價值 在數(shù)據(jù)驅(qū)動決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類分析:從操作實踐到業(yè)務價值挖掘 在數(shù)據(jù)分析場景中,聚類分析作為 “無監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價值導向 統(tǒng)計模型作為數(shù)據(jù)分析的核心工具,并非簡單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10CDA 數(shù)據(jù)分析師:商業(yè)數(shù)據(jù)分析實踐的落地者與價值創(chuàng)造者 商業(yè)數(shù)據(jù)分析的價值,最終要在 “實踐” 中體現(xiàn) —— 脫離業(yè)務場景的分 ...
2025-09-10機器學習解決實際問題的核心關鍵:從業(yè)務到落地的全流程解析 在人工智能技術落地的浪潮中,機器學習作為核心工具,已廣泛應用于 ...
2025-09-09SPSS 編碼狀態(tài)區(qū)域中 Unicode 的功能與價值解析 在 SPSS(Statistical Product and Service Solutions,統(tǒng)計產(chǎn)品與服務解決方案 ...
2025-09-09