首页 > 解决方案 > 从一大块 xml 元素中解析一些名称时遇到问题

问题描述

我已经在 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.

标签: pythonxmlpython-3.xweb-scrapingbeautifulsoup

解决方案


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

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

推荐阅读