使用Python和Beautiful Soup解析/提取API XML数据
我刚开始接触Python和BeautifulSoup,正在尝试学习如何解析XML,特别是想用Oodle.com的API来列出汽车的分类信息。我在处理简单的XML和BeautifulSoup时取得了一些成功,但在这个API上却怎么也拿不到我想要的数据。我花了几个小时看Soup的文档,但还是搞不明白。这个XML的结构是这样的:
<?xml version="1.0" encoding="utf-8"?>
<oodle_response stat="ok">
<current>
....
</current>
<listings>
<element>
<id>8453458345</id>
<title>2009 Toyota Avalon XL Sedan 4D</title>
<body>...</body>
<url>...</url>
<images>
<element>...</element>
<element>...</element>
</images>
<attributes>
<features>...</features>
<mileage>32637</mileage>
<price>19999</price>
<trim>XL</trim>
<vin>9234234234234234</vin>
<year>2009</year>
</attributes>
</element>
<element>.. Next car here ..</element>
<element>..Aaaand next one here ..</element>
</listings>
<meta>...</meta>
</oodle_response>
我首先用urllib发起请求,获取数据并保存到本地文件。然后:
xml = open("temp.xml", "r")
from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(xml)
接下来我就不知道该怎么做了。我尝试了很多方法,但每次得到的数据都比我想要的多得多,这让我很难找到问题所在。我想获取的是id、标题、里程、价格、年份和车架号(vin)。那么我该怎么获取这些数据,并用循环加快这个过程呢?理想情况下,我想用一个像这样的for循环:
for soup.listings.element in soup.listings:
id = soup.listings.element.id
...
我知道这个显然不行,但我希望能有一个方法来获取广告的信息,并把它存储到一个列表中,然后再处理下一个广告。谢谢大家的帮助!
1 个回答
0
你可以这样做:
for element in soup('element'):
id = element.id.text
mileage = element.attributes.mileage.text
price = element.attributes.price.text
year = element.attributes.year.text
vin = element.attributes.vin.text