【问题标题】:xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 0xml.etree.ElementTree.ParseError:格式不正确(无效标记):第 1 行,第 0 列
【发布时间】:2018-11-19 11:58:35
【问题描述】:

我正在尝试使用来自 RSS 提要的一组 xml 文件来解析一个目录。 我有另一个目录的类似代码工作正常,所以我无法找出问题所在。我想退回这些项目,以便将它们写入 CSV 文件。我得到的错误是:

xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 0

这是我收集 RSS 源的网站:https://www.ba.no/service/rss

它适用于:https://www.nrk.no/toppsaker.rsshttps://www.vg.no/rss/feed/?limit=10&format=rss&categories=&keywords=

这是此 RSS 的功能:

import os
import xml.etree.ElementTree as ET
import csv

def baitem():
basepath = "../data_copy/bergens_avisen"

table = []

for fname in os.listdir(basepath):
    if fname != "last_feed.xml":
        files = ET.parse(os.path.join(basepath, fname))
        root = files.getroot()
        items = root.find("channel").findall("item")
        #print(items)
    for item in items:
        date = item.find("pubDate").text
        title = item.find("title").text
        description = item.find("description").text
        link = item.find("link").text
        table.append((date, title, description, link))
return table

我用print(items) 进行了测试,它返回了所有对象。 会不会是XML文件的写法?

【问题讨论】:

    标签: python-3.6 elementtree parse-error xml.etree python-os


    【解决方案1】:

    问了一个朋友,说用try except语句测试。找到一个 .DS_Store 文件,该文件仅适用于 Mac 电脑。我正在为将来可能遇到同样问题的人提供解决方案。

    def baitem():
    
    basepath = "../data_copy/bergens_avisen"
    
    table = []
    
    for fname in os.listdir(basepath):
        try:
            if fname != "last_feed.xml" and fname != ".DS_Store":
                files = ET.parse(os.path.join(basepath, fname))
                root = files.getroot()
                items = root.find("channel").findall("item")
                for item in items:
                    date = item.find("pubDate").text
                    title = item.find("title").text
                    description = item.find("description").text
                    link = item.find("link").text
                    table.append((date, title, description, link))
        except Exception as e:
            print(fname, e)
    return table
    

    【讨论】:

    • 我没有检查 DS_Store,而是确保文件名包含“.xml”,但这是我的问题,非常感谢!
    猜你喜欢
    • 2017-05-02
    • 2016-04-17
    • 1970-01-01
    • 2018-12-05
    • 2019-01-15
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多