如何修复以下错误AttributeError:'dict'对象没有属性'text' [英] How can I fix the following error AttributeError: 'dict' object has no attribute 'text'

查看:443
本文介绍了如何修复以下错误AttributeError:'dict'对象没有属性'text'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am a few months into programming. I am currently in the process of learning how to automate certain things in a project. My goal is to scrape text, src, and href and store the data in my site's database,but when I try I get this error

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

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

but it does. this is my code. I created a function

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)

不是文本属性在我的功能?然后,如果我尝试注释掉文本,它将告诉我

Isn't the text attribute in my function? Then If I try to comment out text it tells me

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

我该如何解决这个问题,以便将要存储的数据正确地存储在数据库中?

how can I fix this so the data i want get stored in my database without any errors? I'm using django if that makes a difference.

推荐答案

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

You have to access dictionary keys like this:

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

不喜欢这样

entry.text
entry.src

这篇关于如何修复以下错误AttributeError:'dict'对象没有属性'text'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆