2018-07-13

coding=utf-8

import requests
from bs4 import BeautifulSoup
import re
import os
import pymongo
import json
import pandas as pd
import numpy as np
import xlrd
import datetime
from pyecharts import Line,Grid,EffectScatter,Overlap

def getPriceSoup_table(spiderDay):
soup_table=BeautifulSoup('',"lxml")
for m in range(1,4):
url = "http://www.hfzgncp.com.cn/index.php?m=content&c=index&a=lists&catid=59&sendtime="+str(spiderDay)+"&page="+str(m)
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0)' +
'Gecko/20100101 Firefox/61.0'}
r = requests.get(url,headers=headers)
html = r.text.encode(encoding='utf_8').decode()
soup = BeautifulSoup(html,"lxml")
table = soup.find('table', attrs={'class' :{'h_list_table r_list_table'}})
soup_table.append(table)
if soup_table.find('td') == None:
print('!!!!!!!!!!!!!!!!!!!!!!'+str(spiderDay)+'這一天沒有水產(chǎn)品價格數(shù)據(jù)!!!!!!!!!!!!!!!!!!!!!!')
return
print(str(spiderDay)+'這一天有水產(chǎn)品價格數(shù)據(jù)')
return soup_table

def soup_tabletoDataFrame(soup_table): #構造dataframe 準備存儲表格
#收集表頭
columns = [x.text for x in soup_table.tr.findAll('th')]
columns = [x.replace('\xa0','') for x in columns]
#print('水產(chǎn)品表頭列表:'+str(columns))
#表的寬度
width = len(columns)
print('水產(chǎn)品表頭數(shù)目:'+str(width))
#height = len(soup_table.findAll(lambda tag:tag.name=='tr' and len(tag.findAll('td'))>=1))
#print('height:'+height)
rows=[]
for row in soup_table.findAll('tr'):
if row not in rows and row.find('td')!=None:
rows.append(row)
height = len(rows) #水產(chǎn)品種類數(shù)目
if height <=0:
return
print('水產(chǎn)品種類數(shù)目:'+str(height))
for i in range(height):
cells = rows[i].findAll('td')
#print(cells)
df = pd.DataFrame(data = np.full((height,width),'',dtype = 'U'),columns = columns)
#逐行分析表格
for i in range(height):
cells = rows[i].findAll('td')
if len(cells) == width:
df.iloc[i] = [cell.text.replace(' ','').replace('\n','') for cell in cells] #去點空格和換行
else:
w=len(cells)
df.iloc[i,width-w:] = [cell.text.replace(' ','').replace('\n','') for cell in cells]
return df

def onedayPriceSpider(spiderDay):

#查看表格數(shù)據(jù)行數(shù)
#height = len(table.findAll(lambda tag:tag.name=='tr' and len(tag.findAll('td'))>=1))
#rows = [row for row in table.findAll('tr') if row.find('td')!=None]
#print('rows:'+str(len(rows)))

#sendtime = soup.find('input', attrs={'id' :{'sendtime'}})['value'].rstrip('/-') #獲取數(shù)據(jù)時間
#sendtimeStr=re.sub("\-","",sendtime)

def getPriceLine(product_name,days):
price_data = []
price_date = []
for i in range(days):
spiderDay = datetime.date.today()- datetime.timedelta(days=i+1)
spiderDayStr =str(spiderDay) #2018-07-11格式
sendtimeStr=re.sub("-","",spiderDayStr) #20180711格式
#outputfilePath="D:/xlsx/"+sendtimeStr+".水產(chǎn)品價格xlsx"
if os.path.exists(outputfilePath):
ExcelFile = xlrd.open_workbook(outputfilePath)
sheet = ExcelFile.sheet_by_index(0)
columnIndex = None
rowIndex = None
for j in range(sheet.ncols):
for i in range(sheet.nrows):
if sheet.cell_value(i, j) == '平均價':
columnIndex = j
break
if sheet.cell_value(i, j) == product_name:
rowIndex = i
break
if not (rowIndex == None) and not (columnIndex == None):
print(sheet.cell_value(rowIndex, columnIndex))
price_data.append(sheet.cell_value(rowIndex, columnIndex))
price_date.append(sendtimeStr)
print(price_data)
print(price_date)
attr = price_date[::-1]
v1 = price_data[::-1]
line = Line(product_name+'價格走勢圖')
line.add(product_name,attr,v1,is_smooth = True,mark_point = ['max','min'],mark_line=["average"],yaxis_formatter="元")
grid =Grid()
grid.add(line,grid_top="10%")

判斷是否存在目標文件夾

isExists=os.path.exists('D:/價格走勢圖')
if not isExists:

如果不存在則創(chuàng)建目錄

    os.makedirs('D:/價格走勢圖') 

    print ('創(chuàng)建D:/價格走勢圖文件夾成功')
#return True
else:
    # 如果目錄存在則不創(chuàng)建店诗,并提示目錄已存在

print ('目錄已存在')

    grid.render('D:/價格走勢圖/'+product_name+str(days)+'天價格走勢圖.html')
    print('已得到'+product_name+'價格走勢圖')

es = EffectScatter()

es.add('',attr,v1,effect_scale=8) #閃爍

overlop = Overlap()

overlop.add(line) #必須先添加line,在添加es

overlop.add(es)

overlop.render('./line-es01.html')

return  
    
#client= pymongo.MongoClient()
#獲取一個數(shù)據(jù)庫   
#db=client.priceSpider
#創(chuàng)建 或獲取一個集合音同,并在collection下新建books
#account=db.prcie
#data=xlrd.open_workbook("D:/"+sendtimeStr+".xlsx")
#table=data.sheets()[0]
#讀取excel第一行數(shù)據(jù)作為存入mongodb的字段名
#rowstag=table.row_values(0)
#nrows=table.nrows
#print('-------------nrows----------------'+str(nrows))
#ncols=table.ncols #print rows
#returnData={}
#for i in range(1,nrows):
    #將字段名和excel數(shù)據(jù)存儲為字典形式,并轉(zhuǎn)換為json格式
    #returnData[i]=json.dumps(dict(zip(rowstag,table.row_values(i))))
    #通過編解碼還原數(shù)據(jù)
    #returnData[i]=json.loads(returnData[i])
    #print returnData[i]
    #account.insert(returnData[i])
    #return daySpider

if name=="main":

spiderDaynumber = 60 
for i in range(spiderDaynumber):    
    spiderDay = datetime.date.today()- datetime.timedelta(days=i+1)
    spiderDayStr =str(spiderDay)  #2018-07-11格式 
    sendtimeStr=re.sub("\-","",spiderDayStr) #20180711格式
    soup_table = getPriceSoup_table(spiderDay)
    if not soup_table == None:
        df = soup_tabletoDataFrame(soup_table)
        isExists=os.path.exists('D:/xlsx')
        if not isExists:
    #         如果不存在則創(chuàng)建目錄
            os.makedirs('D:/xlsx') 
            print ('創(chuàng)建D:/xlsx文件夾成功')
        #return True
        else:
            outputfilePath="D:/xlsx/"+sendtimeStr+"水產(chǎn)品價格.xlsx"
            df.to_excel(outputfilePath)
    print('-------------------------------')
getPriceLine('帶魚(大)',59)
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件眼五,死亡現(xiàn)場離奇詭異,居然都是意外死亡彤灶,警方通過查閱死者的電腦和手機俱恶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進店門戒幔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來菌仁,“玉大人存崖,你說我怎么就攤上這事〔ǎ” “怎么了棚唆?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長心例。 經(jīng)常有香客問我宵凌,道長,這世上最難降的妖魔是什么止后? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任瞎惫,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘瓜喇。我一直安慰自己逗扒,他們只是感情好,可當我...
    茶點故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布欠橘。 她就那樣靜靜地躺著,像睡著了一般现恼。 火紅的嫁衣襯著肌膚如雪肃续。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天叉袍,我揣著相機與錄音始锚,去河邊找鬼。 笑死喳逛,一個胖子當著我的面吹牛瞧捌,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播润文,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼姐呐,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了典蝌?” 一聲冷哼從身側響起曙砂,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎骏掀,沒想到半個月后鸠澈,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡截驮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年笑陈,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片葵袭。...
    茶點故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡涵妥,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出坡锡,到底是詐尸還是另有隱情妹笆,我是刑警寧澤,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布娜氏,位于F島的核電站拳缠,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏贸弥。R本人自食惡果不足惜窟坐,卻給世界環(huán)境...
    茶點故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧哲鸳,春花似錦臣疑、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至婿奔,卻和暖如春缺狠,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背萍摊。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工挤茄, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人冰木。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓穷劈,卻偏偏與公主長得像,于是被迫代替她去往敵國和親踊沸。 傳聞我的和親對象是個殘疾皇子歇终,可洞房花燭夜當晚...
    茶點故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容