How can I fix the following error AttributeError: 'dict' object has no attribute 'text'

How can I fix the following error AttributeError: 'dict' object has no attribute 'text'

我刚开始编程几个月。我目前正在学习如何使项目中的某些事情自动化。我的目标是抓取文本、src 和 href 并将数据存储在我站点的数据库中,但是当我尝试时出现此错误

AttributeError: 'dict' object has no attribute 'text'

但确实如此。这是我的代码。我创建了一个函数

def get_world_too():
        url = 'http://www.example.com'
        html = requests.get(url, headers=headers)
        soup = BeautifulSoup(html.text, 'html5lib')

        titles = soup.find_all('section', 'box')[:9]
        entries = [{'href': box.a.get('href'),
                    'src': box.img.get('src'),
                    'text': box.strong.a.text,
                    'url': url
                    } for box in titles]
        return entries

然后我就这样做了

def noindex(request):
    world = get_world_too()

    for entry in world:
        post = Post()
        post.title = entry.text
        post.image_url = entry.src
        # post.url = entry.url
        # post.link = entry.href
        # post.description = entry.description
        #
        # d = datetime.datetime(*(entry.published_parsed[0:6]))
        # date_string = d.strftime('%Y-%m-%d %H:%M:%S')
        #
        # post.publication_date = date_string
        post.save()

        template = "blog/post/noindex.html"
        context = {

        }
        return render(request, template, context)

我的函数中没有文本属性吗?然后,如果我尝试注释掉文本,它会告诉我

AttributeError: 'dict' object has no attribute 'src'

我该如何解决这个问题,以便我想要的数据正确无误地存储在我的数据库中?如果这有所作为,我正在使用 django。

您必须像这样访问字典键:

entry['text']
entry['src']

不是这样的

entry.text
entry.src

在 python 中,您无法使用语法 dict.key 访问字典项目, 如果条目是一个字典,你可以使用

  • entry['key1']
  • entry.get('key')