代码之家  ›  专栏  ›  技术社区  ›  Melissa Stewart

在Python中用自结束标记解析XML数据

  •  1
  • Melissa Stewart  · 技术社区  · 6 年前

    <link>https://www.nba.com/bucks/</link>

    在代码中这变成了,

    link = item['link']
    

    如何解析自动结束标记?

    <enclosure url="https://www.nba.com/bucks/sites/bucks/files/styles/media_thumbnail/public/middleton_3point_tw.jpg?itok=eiU05Btp" length="37714" type="image/jpeg" />
    

    另外,我如何只得到图像的网址和删除一切之后 ? 在URL中?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Arran Duff    6 年前

    使用诸如 https://docs.python.org/2/library/xml.etree.elementtree.html

    • xpath定义了用于标识和提取xml文档中的元素/标记的标准表达式

    • 将xpath与一个好的xml解析器一起使用,您可以轻松地在文档中找到任何元素。例如查找所有 圈地 文档中的元素 “//外壳”

    • 如果您正在解析XML,那么很多xpath非常值得一读。这是一个很好的入门教程 https://www.w3schools.com/xml/xpath_intro.asp

    例如,您可以:

    import xml.etree.ElementTree as ET
    tree = ET.parse('your_xml_file.xml')
    enclosures = tree.findall(".//enclosure") # Use the XPath to find all enclosure elements 
    for enclosure in  enclosures:
        print(enclosure.attrib)
    

    {'url': 'https://www.nba.com/bucks/sites/bucks/files/styles/media_thumbnail/public/middleton_3point_tw.jpg?itok=eiU05Btp', 'length': '37714', 'type': 'image/jpeg'}
    

    然后可以在 ? 例如

    url = enclosure.attrib['url'].split('?')[0]
    print(url)
    

    输出

    https://www.nba.com/bucks/sites/bucks/files/styles/media_thumbnail/public/middleton_3point_tw.jpg