tushare 之get_today_all出現ValueError No found when decoding object value問題

在使用tushare.get_today_all出現ValueError: No ':' found when decoding object value問題改如何解決呢?

這是你會發現,其實get_today_all從網頁獲取的數據時正常的,而進行json -> dataframe時出的錯,經過拍錯後,發現是因爲網頁上讀取的json文件有問題的。

要進行一些字符的替換的;所以要找到源碼對裏面一個函數進行Fixed就OK,修改後的code如下。

def _parsing_dayprice_json(types=None, page=1):
    """
           處理當日行情分頁數據,格式爲json
     Parameters
     ------
        pageNum:頁碼
     return
     -------
        DataFrame 當日所有股票交易數據(DataFrame)
    """
    ct._write_console()
    request = Request(ct.SINA_DAY_PRICE_URL%(ct.P_TYPE['http'], ct.DOMAINS['vsf'],
                                 ct.PAGES['jv'], types, page))
    text = urlopen(request, timeout=10).read()
    if text == 'null':
        return None
    reg = re.compile(r'\,(.*?)\:')
    text = reg.sub(r',"\1":', text.decode('gbk') if ct.PY3 else text)
    text = text.replace('"{"symbol', '{"symbol') # modify by xsophiax
    text = text.replace('{symbol', '{"symbol"')
    text = text.replace('""', '"') # add by xsophiax 
    if ct.PY3:
#         text = text.decode('GBK')
        jstr = json.dumps(text)
    else:
        jstr = json.dumps(text, encoding='GBK')
    js = json.loads(jstr)
    df = pd.DataFrame(pd.read_json(js, dtype={"code":object}),
                      columns=ct.DAY_TRADING_COLUMNS)
    df = df.drop('symbol', axis=1)
#     df = df.ix[df.volume > 0]
    return df

def get_today_all():
    ct._write_head()
    df = _parsing_dayprice_json('hs_a', 1)
    if df is not None:
        for i in range(2, ct.PAGE_NUM[1]):
            newdf = _parsing_dayprice_json('hs_a', i)
            if newdf.shape[0] > 0:
                df = df.append(newdf, ignore_index=True)
            else:
                break
    df = df.append(_parsing_dayprice_json('shfxjs', 1),
                                               ignore_index=True)
    return df

現在調用get_today_all就可以了。

完成源碼路徑:https://blog.csdn.net/xsophiax/article/details/106613508

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章