【发布时间】:2011-10-11 18:14:25
【问题描述】:
Python/xml 新手在这里玩弄 Python 和 BeautifulSoup,试图学习如何解析 XML,特别是弄乱 Oodle.com API 来列出汽车分类。我在简单的 XML 和 BS 方面取得了成功,但是在使用它时,无论我尝试什么,我似乎都无法获得我想要的数据。我尝试阅读 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、title、mileage、price、year、vin。那么我如何获得这些并通过循环加快进程呢?理想情况下,我想要一个 for 循环,例如:
for soup.listings.element in soup.listings:
id = soup.listings.element.id
...
我知道这显然不起作用,但可以获取列表信息并将其存储到列表中,然后转到下一个广告。感谢帮助的家伙
【问题讨论】:
标签: python xml api xml-parsing beautifulsoup