AttributeError: 'NavigableString' object has no attribute 'keys' in Python

AttributeError: 'NavigableString' object has no attribute 'keys' in Python

我试图将数组中的数据转储到 csv 文件中,但出现以下错误: AttributeError:'NavigableString' 对象在 python 中没有属性 'keys'。当我尝试打印数组时,该数组有数据,但在尝试创建 csv 文件时它抛出错误。

这是我写的代码:

import requests
import csv
from bs4 import BeautifulSoup as bs

global newsitems
def loadRSS():
    url="https://rss.nytimes.com/services/xml/rss/nyt/Africa.xml"
    resp=requests.get(url)
    with open('topnewsfeed.xml','wb') as f:
        f.write(resp.content)

def extractData():
    infile = open("topnewsfeed.xml","r",encoding='utf-8')
    contents = infile.read()
    soup = bs(contents,'xml')
    guids= soup.find_all('guid')
    titles = soup.find_all('title')
    pubDates= soup.find_all('pubDate')
    descs= soup.find_all('description')
    links= soup.find_all('link')
    newsitems=[]
    for (guid,title,pubDate,desc,link) in zip(guids,titles,pubDates,descs,links):
        newsitems.append(guid.string)
        newsitems.append(title.string)
        newsitems.append(pubDate.string)
        newsitems.append(desc.string)
        newsitems.append(link.string)
    return newsitems

def savetoCSV(array,filename):
    fields=['Guid','Title','PubDate','Description','Link']
    with open(filename,'w') as csvfile:
        writer=csv.DictWriter(csvfile,fieldnames=fields)
        writer.writeheader()
        writer.writerows(array)
             
def run():
    loadRSS()
    newsitems=extractData()
    savetoCSV(newsitems,'topnews.csv')
run()

DictWriter 的 writerows 需要一个字典序列(字段名作为映射到值的键),而不是一个 NavigableString 对象序列,这就是 newsitems。

而不是制作一系列可导航的字符串:

    for (guid,title,pubDate,desc,link) in zip(guids,titles,pubDates,descs,links):
        newsitems.append(guid.string)
        newsitems.append(title.string)
        newsitems.append(pubDate.string)
        newsitems.append(desc.string)
        newsitems.append(link.string)

按照writerows 的预期制作字典列表。字典中的键应与您的 CSV 字段匹配 ('Guid','Title','PubDate','Description','Link')

    for (guid,title,pubDate,desc,link) in zip(guids,titles,pubDates,descs,links):
        newsitems.append({
                          'Guid': guid.string,
                          'Title': title.string,
                          'PubDate': pubDate.string,
                          'Description': desc.string,
                          'Link': link.string
                         }
        )