【python】book爬蟲、數據清洗與可視化實戰2

import requests
import time
import pandas as pd

# 加載pymongo庫i
import pymongo
#建立連接
client = pymongo.MongoClient('localhost',27017)
# 在MongoDB中新建名爲weather的數據庫
book_weather=client['weather']
# 在weather庫中新建名爲sheet_ weather_ 3的表
sheet_weather = book_weather['sheet weather_ 3']
data=pd.read_csv(open('H:/new file 2/python_project/wethear API/china-city-list.csv',encoding ='utf-8'))
data1 = data.iloc[1:,0]#通過iloc(行列號)索引
for item in data1[0:10]:
    url = 'https://free-api.heweather.net/s6/weather/now?location='+ item +'&key=b09b35a6293e41d29c9e9813de84673c'
    strhtml = requests.get(url)
    strhtml.encoding = 'utf8'
    time.sleep(1)
    dic = strhtml.json()
    for item in dic["HeWeather6"][0]["now"]["wind_dir"]:
        print(item);
      # 向表寫入一條數據(真正核心的就下面一句唄)
        sheet_weather.insert_one(dic)

最終報錯:

H:\python\anzhuang\python.exe H:/pycharm/excise/pachong/.idea/book2_c4.py
西

Traceback (most recent call last):
  File "H:/pycharm/excise/pachong/.idea/book2_c4.py", line 24, in <module>
    sheet_weather.insert_one(dic)
  File "H:\python\anzhuang\lib\site-packages\pymongo\collection.py", line 698, in insert_one
    session=session),
  File "H:\python\anzhuang\lib\site-packages\pymongo\collection.py", line 612, in _insert
    bypass_doc_val, session)
  File "H:\python\anzhuang\lib\site-packages\pymongo\collection.py", line 600, in _insert_one
    acknowledged, _insert_command, session)
  File "H:\python\anzhuang\lib\site-packages\pymongo\mongo_client.py", line 1492, in _retryable_write
    return self._retry_with_session(retryable, func, s, None)
  File "H:\python\anzhuang\lib\site-packages\pymongo\mongo_client.py", line 1385, in _retry_with_session
    return func(session, sock_info, retryable)
  File "H:\python\anzhuang\lib\site-packages\pymongo\collection.py", line 597, in _insert_command
    _check_write_command_response(result)
  File "H:\python\anzhuang\lib\site-packages\pymongo\helpers.py", line 221, in _check_write_command_response
    _raise_last_write_error(write_errors)
  File "H:\python\anzhuang\lib\site-packages\pymongo\helpers.py", line 202, in _raise_last_write_error
    raise DuplicateKeyError(error.get("errmsg"), 11000, error)
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: weather.sheet weather_ 3 index: _id_ dup key: { : ObjectId('5ded0017c415df0551e007c4') }

Process finished with exit code 1
 

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