shutiaowanwan 2022-02-22 13:40 采纳率: 100%
浏览 3462
已结题

Python爬虫 错误:json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

一、问题
练习协程,使用aiohttp.ClientSession().get(url).json()报错,代码如下:

async def aiodownload(bid, cid, title):
    # 异步任务
    data = {
        'book_id': bid,
        'cid': f'{bid}|{cid}',
        'need_bookinfo': 1
    }
    data = json.dumps(data)
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
    }
    base_url = f'http://dushu.baidu.com/api/pc/getChapterContent/?data={data}'
    async with aiohttp.ClientSession() as session:
        async with session.get(base_url, headers=header) as resp:
            # !!出错地方
            dic = await resp.json()  #content_type=None
            async with aiofiles.open('.novel/' + title, 'w', newline='', encoding='utf-8') as f:
                await f.write(dic['data']['novel']['content'])
    print('done!')

这段代码是跟着B站的课写的,一样的代码,up跑成功了,俺不成功。
不用协程单独拿出来访问是没有问题的,如下,一加上await就出错,json不成功

# 这样是正常的
bid = '4306063500'
cid = '1569782244'
data = {
         'book_id': bid,
         'cid': f'{bid}|{cid}',
         'need_bookinfo': 1
     }
data = json.dumps(data)
url1 = f'http://dushu.baidu.com/api/pc/getChapterContent?data={data}'
resp = requests.get(url1)
    # print(resp.json())
dic = resp.json()
print(dic['data']['novel']['content'])
resp.close()

二、报错

Task exception was never retrieved
in json raise ContentTypeError(
aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html; charset=utf-8', 

Process finished with exit code 0

三、尝试解决(全是在网上搜的解决办法
json()里指定类型,dic = await resp.json(content_type=None, encoding='utf-8)
还是报错:json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0),这个错误没找到解决办法

刚开始学,不知如何下手解决,礼貌求解!

  • 写回答

5条回答 默认 最新

  • CSDN专家-showbo 2022-02-22 14:54
    关注

    async+await方法的url多了个斜杠,去掉就行了。要不多的那个斜杠接口出错返回的是html代码了,调用json()出错了,内容不是json字符串

    img

    测试代码如下

    img

    import json
    import aiohttp
    import asyncio
    async def aiodownload(bid, cid, title):
        # 异步任务
        data = {
            'book_id': bid,
            'cid': f'{bid}|{cid}',
            'need_bookinfo': 1
        }
        data = json.dumps(data)
        header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
        }
        base_url = f'http://dushu.baidu.com/api/pc/getChapterContent?data={data}'
        
        async with aiohttp.ClientSession() as session:
            async with session.get(base_url, headers=header) as resp:
                # !!出错地方
                dic = await resp.json()  #content_type=None
                #async with aiofiles.open('.novel/' + title, 'w', newline='', encoding='utf-8') as f:
                    #await f.write(dic['data']['novel']['content'])
        print(dic)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(aiodownload('4306063500','1569782244','xxx'))
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(4条)

报告相同问题?

问题事件

  • 系统已结题 3月2日
  • 已采纳回答 2月22日
  • 创建了问题 2月22日

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法