gpt4 book ai didi

python - 操作系统错误 : [Errno 36] File name too long:

转载 作者:数据小太阳 更新时间:2023-10-29 02:01:30 28 4
gpt4 key购买 nike

我需要将网页转换为 XML(使用 Python 3.4.3)。如果我将 URL 的内容写入文件,那么我可以完美地读取和解析它,但是如果我尝试直接从网页读取,我的终端会出现以下错误:

File "./AnimeXML.py", line 22, in xml = ElementTree.parse (xmlData) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/xml/etree/ElementTree.py", line 1187, in parse tree.parse(source, parser) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/xml/etree/ElementTree.py", line 587, in parse source = open(source, "rb") OSError: [Errno 36] File name too long:

我的python代码:

# AnimeXML.py
#! /usr/bin/Python

# Import xml parser.
import xml.etree.ElementTree as ElementTree

# XML to parse.
sampleUrl = "http://cdn.animenewsnetwork.com/encyclopedia/api.xml?anime=16989"

# Read the xml as a file.
content = urlopen (sampleUrl)

# XML content is stored here to start working on it.
xmlData = content.readall().decode('utf-8')

# Close the file.
content.close()

# Start parsing XML.
xml = ElementTree.parse (xmlData)

# Get root of the XML file.
root = xml.getroot()

for info in root.iter("info"):
print (info.attrib)

有什么方法可以修复我的代码,以便我可以将网页直接读入 python 而不会出现此错误?

最佳答案

Parsing XML 中所述ElementTree 文档部分:

We can import this data by reading from a file:

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

Or directly from a string:

root = ET.fromstring(country_data_as_string)

您将整个 XML 内容作为一个巨大的路径名传递。您的 XML 文件可能大于 2K,或者任何适合您平台的最大路径名大小,因此会出现错误。如果不是,您将得到一个不同的错误,即没有名为 [XML 文件中第一个/之前的所有内容] 的目录。

只需使用 fromstring而不是 parse

或者,注意 parse可以接受一个文件对象,而不仅仅是一个文件名。 urlopen返回的东西是一个文件对象。


另请注意该部分的下一行:

fromstring() parses XML from a string directly into an Element, which is the root element of the parsed tree. Other parsing functions may create an ElementTree.

所以,您也不想要那个 root = tree.getroot()


所以:

# ...
content.close()
root = ElementTree.fromstring(xmlData)

关于python - 操作系统错误 : [Errno 36] File name too long:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29891308/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com