---
title: "Python 解析XML"
author: "ipython"
date: "2016-02-17T14:44:42Z"
tags: []
categories: ["编程语言"]
slug: "python-xml"
draft: false
lastmod: "2016-05-02T18:10:51Z"
id: 2276956
url: "https://ipython.iteye.com/blog/2276956"
---

Python 解析XML

 

使用模块lxml

安装: 

pip install lxml

pip install requests

```
from lxml import html
import requests
page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.content)
buyers = tree.xpath('//div[@title="buyer-name"]/text()')
prices = tree.xpath('//span[@class="item-price"]/text()')
```

 

参考： http://docs.python-guide.org/en/latest/scenarios/scrape/#web-scraping

 

如果xml里面带有命名空间，namespace, 可以这样：

如： &lt;itunes:duration&gt;14:00&lt;/itunes:duration&gt;  
duration= tree.xpath('//itunes:duration/text()', namespaces ={'itunes': 'http://www.itunes.com/DTDs/Podcast-1.0.dtd'})