簡體   English   中英

如何修復以下錯誤AttributeError:'dict'對象沒有屬性'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)

我的函數中不是text屬性嗎? 然后,如果我嘗試注釋掉文本,它會告訴我

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

我該如何解決這個問題,以便將要存儲的數據正確地存儲在數據庫中? 我正在使用django如果這有所作為。

您必須像這樣訪問字典鍵:

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

不是這樣

entry.text
entry.src

在python中,您無法使用語法dict.key訪問字典項,如果entry是字典,則可以使用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM