近公司有一項爬取數據的工作,借鑒以往的代碼將爬蟲重新更新并整理
將現有爬蟲分成幾部分
0.文件讀取器
其實文件讀取和4中的文件存儲是在一個部分的
這里簡單介紹下xls的讀取
def deal_xls_col(name,sheet_name):
body = xlrd.open_workbook(name)
try:
sh = body.sheet_by_name(sheet_name)
except:
print "EORR"
return sh.col_values(0)格式請忽略
這里讀取了一豎行的xls的數據
返回的格式為list
1.總調度器
這里主要是寫邏輯,及0234的順序。
2.網頁下載器
網頁下載器主要是來模擬瀏覽器訪問對應url
一個簡單的例子
class HtmlDownloader(object):
def download(self,url):
if url is None:
return None
response = urllib2.urlopen(url,timeout=300)
if response.getcode() != 200:
return None
return response.read()
例子只是去訪問url并沒有對cookie等相關限制信息做處理(需要請自行添加)
3.網頁分析器
網頁分析器其實是來處理下載器返回的html的源碼,比如用selenium來處理的話則有
company_info_text = driver.find_element_by_class_name('company_info_text')
company_text = driver.find_element_by_class_name('row b-c-white company-content')
是用selenium的一些方法來獲取你需要的數據而已
4.文件存儲器
這里以xls為例:
def creat_xls_6(xls_name):
styleBoldRed = xlwt.easyxf('font:color-index red, bold on')
headerStye = styleBoldRed wb = xlwt.Workbook()
ws = wb.add_sheet(xls_name)
ws.write(0, 0, "name", headerStye)
ws.write(0, 1, "oper_name", headerStye)
ws.write(0, 2, "start_date", headerStye)
ws.write(0, 3, "xfsSearchStatus", headerStye)
wb.save(xls_name)
創建xls表格
def insert_xls_6(xls_name,id, name, oper_name, start_date,xfsSearchStatus):
oldWb = xlrd.open_workbook(xls_name)
newWb = copy(oldWb)
newWs = newWb.get_sheet(0)
newWs.write(id, 0, name)
newWs.write(id, 1, oper_name)
newWs.write(id, 2, start_date)
newWs.write(id, 3, xfsSearchStatus)
newWb.save(xls_name)
插入數據到表格
這里面沒有什么高深的秘密,只要你封裝好自己的函數好了
上面的例子還不是好的版本,因為每次使用都要重新修改,應該傳入一個數據來代替那些變量,這樣可以適配各種數據的表格創建和添加了
還有要說的是:一些網站會限制你爬取數據,但是大多數網站都是友好的,但是這并不表示你可以肆無忌憚的毫無限制的去爬取。爬取的時間好設置成晚上或者。。。。
還有是不要對目標網站造成不必要的‘傷害’。