【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
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值