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

Deadly 提交于 2020-06-22 13:25:22

问题


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

then I did this

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.


回答1:


You have to access dictionary keys like this:

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

Not like this

entry.text
entry.src



回答2:


In python you cannot access dictionary items using the syntax dict.key , If entry is a dictionary, you can use

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


来源:https://stackoverflow.com/questions/37600656/how-can-i-fix-the-following-error-attributeerror-dict-object-has-no-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!