【问题标题】:Trouble parsing some names out of a chunk of xml elements从一大块 xml 元素中解析一些名称时遇到问题
【发布时间】:2018-05-14 21:05:47
【问题描述】:

我已经在 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 解析相同的内容。

【问题讨论】:

    标签: python xml python-3.x web-scraping beautifulsoup


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多