最近公司有一項(xiàng)Python爬取數(shù)據(jù)的工作,借鑒以往的代碼將爬蟲重新更新并整理
將現(xiàn)有爬蟲分成幾部分
0.文件讀取器
其實(shí)文件讀取和4中的文件存儲是在一個部分的
這里簡單介紹下xls的讀取
defdeal_xls_col(name,sheet_name):
body=xlrd.open_workbook(name)
try:
sh=body.sheet_by_name(sheet_name)
except:
print"EORR"
returnsh.col_values(0)格式請忽略
這里讀取了一豎行的xls的數(shù)據(jù)
返回的格式為list
1.總調(diào)度器
這里主要是寫邏輯,及0234的順序。
2.網(wǎng)頁下載器
網(wǎng)頁下載器主要是來模擬瀏覽器訪問對應(yīng)url
一個簡單的例子
classHtmlDownloader(object):
defdownload(self,url):
ifurlisNone:
returnNone
response=urllib2.urlopen(url,timeout=300)
ifresponse.getcode()!=200:
returnNone
returnresponse.read()
例子只是去訪問url并沒有對cookie等相關(guān)限制信息做處理(需要請自行添加)
3.網(wǎng)頁分析器
網(wǎng)頁分析器其實(shí)就是來處理下載器返回的html的源碼,比如用selenium來處理的話則有
company_info_text=driver.find_element_by_class_name('company_info_text')
company_text=driver.find_element_by_class_name('rowb-c-whitecompany-content')
就是用selenium的一些方法來獲取你需要的數(shù)據(jù)而已
4.文件存儲器
這里以xls為例:
defcreat_xls_6(xls_name):
styleBoldRed=xlwt.easyxf('font:color-indexred,boldon')
headerStye=styleBoldRedwb=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)
創(chuàng)建xls表格
definsert_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)
插入數(shù)據(jù)到表格
這里面沒有什么高深的秘密,只要你封裝好自己的函數(shù)就好了
上面的例子還不是最好的版本,因?yàn)槊看问褂枚家匦滦薷?,?yīng)該傳入一個數(shù)據(jù)來代替那些變量,這樣就可以適配各種數(shù)據(jù)的表格創(chuàng)建和添加了
還有要說的就是:一些網(wǎng)站會限制你爬取數(shù)據(jù),但是大多數(shù)網(wǎng)站都是友好的,但是這并不表示你可以肆無忌憚的毫無限制的去爬取。爬取的時間最好設(shè)置成晚上或者。。。。
還有就是不要對目標(biāo)網(wǎng)站造成不必要的‘傷害’。
爬蟲并不難,且行且珍惜!
以上內(nèi)容為大家介紹了PythonSelenium爬取數(shù)據(jù),希望對大家有所幫助,如果想要了解更多Python相關(guān)知識,請關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。http://www.2667701.com/