首页 > 解决方案 > 字节类型序列化的python json问题

问题描述

我正在按照教程从静态网站构建一个简单的 webscraper,但我得到以下 TypeError:TypeError(f'Object of type {o.class .name } ' TypeError : Object of type bytes is not JSON serializable

到目前为止,这是我的代码: from bs4 import BeautifulSoup import requests import json

url = 'http://ethans_fake_twitter_site.surge.sh/'
response = requests.get(url, timeout=5)
content = BeautifulSoup(response.content, "html.parser")
tweetArr = []

for tweet in content.findAll('div', attrs = {'class': 'tweetcontainer'}):
    tweetObject = {
        "author": tweet.find('h2', attrs= {'class': 'author'}).text.encode('utf-8'),
        "date": tweet.find('h5', attrs= {'class': 'dateTime'}).text.encode('utf-8'),
        "content": tweet.find('p', attrs= {'class': 'content'}).text.encode('utf-8'),
        "likes": tweet.find('p', attrs= {'class': 'likes'}).text.encode('utf-8'),
        "shares": tweet.find('p', attrs= {'class': 'shares'}).text.encode('utf-8')
    }
    tweetArr.append(tweetObject)
with open('twitterData.json', 'w') as outfile:
    json.dump(tweetArr, outfile)

我唯一可以假设的错误是这篇文章使用的是早期版本的 python,但这篇文章是最近的,所以不应该是这种情况。正在执行代码并创建 json 文件,但那里唯一的数据是“作者:”。对不起,如果答案对你们中的一些人来说是显而易见的,但我才刚刚开始学习。

这是整个错误日志: (tutorial-env) C:\Users\afaal\Desktop\python\webscraper>python webscraper.py Traceback(最近一次调用最后):文件“webscraper.py”,第 20 行,在 json.dump (tweetArr,outfile)文件“C:\Users\afaal\AppData\Local\Programs\Python\Python38\lib\json__init__.py”,第 179 行,在可迭代中的块转储中:文件“C:\Users\afaal\ AppData\Local\Programs\Python\Python38\lib\json\encoder.py",第 429 行,在 _iterencode 中的 _iterencode_list(o, _current_indent_level) 文件“C:\Users\afaal\AppData\Local\Programs\Python\Python38 \lib\json\encoder.py”,第 325 行,在 _iterencode_list 中从块文件“C:\Users\afaal\AppData\Local\Programs\Python\Python38\lib\json\encoder.py”中产生,第 405 行,在_iterencode_dict 从块文件“C:\Users\afaal\AppData\Local\Programs\Python\Python38\lib\json\encoder.py”,第 438 行,在 _iterencode o = _default(o) 文件“C:\Users\afaal\AppData\Local\Programs\ Python\Python38\lib\json\encoder.py",第 179 行,默认引发 TypeError(f'Object of type {o.name } ' TypeError: 字节类型的对象不是 JSON 可序列化的

标签: pythonweb-scraping

解决方案


好的,事实证明我需要删除“.text”之后的所有内容,并且只需要谷歌“Json 序列化”(我只尝试谷歌搜索我的特定 TypeError 并没有得到任何确凿的信息)。正确的代码如下,以防像我这样的任何业余爱好者遇到同样的问题:

url = 'http://ethans_fake_twitter_site.surge.sh/'
response = requests.get(url, timeout=5)
content = BeautifulSoup(response.content, "html.parser")
tweetArr = []

for tweet in content.findAll('div', attrs = {'class': 'tweetcontainer'}):
    tweetObject = {
        "author": tweet.find('h2', attrs= {'class': 'author'}).text,
        "date": tweet.find('h5', attrs= {'class': 'dateTime'}).text,
        "content": tweet.find('p', attrs= {'class': 'content'}).text,
        "likes": tweet.find('p', attrs= {'class': 'likes'}).text,
        "shares": tweet.find('p', attrs= {'class': 'shares'}).text
    }
    tweetArr.append(tweetObject)
with open('twitterData.json', 'w') as outfile:
    json.dump(tweetArr, outfile)

所有功劳归功于@juanpa.arrivillaga,非常感谢您将其彻底清除!


推荐阅读