python - 从一大块 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
.
解决方案
您的调用soup.find("ns:Car")
正在返回一个类型的对象,NoneType
并且您正在尝试调用find_all
该对象的方法NoneType
。尝试将最后几行更改为:
for items in soup.find("Car").find_all("Model"):
print(items)
推荐阅读
- sql - 如何返回一个相关字段存在但另一个不存在的结果?
- gps - Android Things 将 GPS 数据发送到 TextView
- javascript - 根据另一个数组的键过滤数组
- angular - 如何在 Angular 5 上运行 Swagger?
- regex - 正则表达式列出两个字符串之间按字母顺序排列的所有结果
- apache-kafka - 当复制因子 = 2 且最小 ISR 大小 = 1 时,kafka 一致
- r - 将多个列名传递给data.table中的j的官方方法是什么?
- c# - C# ASP.NET 无法对数据库中的搜索结果进行排序
- rest - 列出具有 Angular Rest-API reqres 的用户
- webstorm - 如何在实现方法之前强制 WebStorm 设置公共?