在python开发[第九篇],我们已经在request模块中,讲解了如何根据url去获取网页内容。
如果返回的是内容的格式python的基本数据类型,可以json将返回的字符串转为python的基本数据类型。但是大多数情况下,我们通过http协议请求一个url后,返回的却是?xml格式。基于这种常见的报文格式,python对其进行提供了相应模块,如下:
一、xml模块
XML是实现不同语言或程序之间进行数据交换的协议,XML文件格式如下:
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2023</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2026</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2026</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>