从xml元素块中解析某些名称时遇到问题

2024-03-29 02:08:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用python结合BeautifulSoup编写了一个脚本来解析某些xml元素中的一些名称,但由于某种原因,该脚本在print语句之前抛出了属性错误。我怎样才能让它工作?提前谢谢

到目前为止,我所尝试的:

from bs4 import BeautifulSoup

content="""
 <ns:Car>
  <ns:Model>sedan</ns:Model>
  <ns:Model>coupe</ns:Model>
  <ns:Model>hatchback</ns:Model>
  <ns:Model>convertible</ns:Model>
 </ns:Car>
"""
soup = BeautifulSoup(content,"xml")
for items in soup.find("ns:Car").find_all("ns:Model"):
    print(items)

预期产出:

sedan
coupe
hatchback
convertible

它抛出的错误是:

    for items in soup.find("ns:Car").find_all("ns:Model"):
AttributeError: 'NoneType' object has no attribute 'find_all'

顺便说一句,我不愿意遵守任何与regular expression相关的解决方案。我喜欢使用BeautifulSoup解析相同的内容


Tags: 脚本model错误itemsxmlcontentallfind
1条回答
网友
1楼 · 发布于 2024-03-29 02:08:53

您对soup.find("ns:Car")的调用正在返回类型为NoneType的对象,并且您正在尝试调用此NoneType对象的find_all方法。尝试将最后几行更改为:

for items in soup.find("Car").find_all("Model"):
    print(items)

相关问题 更多 >