使用Python模块BeautifulSoup刮取XML,需要树中的特定标记

时间:2014-03-09 19:31:50

标签: python html xml beautifulsoup lxml

所以我一直在研究这个python脚本,我试图在Leg标签下刮掉Duration和Distance标签。问题是在Step标签中,还有一个名为Duration和Distance的子标签,Step标签是Leg标签的子标签。当我刮取数据时,它也返回那些距离和持续时间标记。 XML如下:

<DirectionsResponse>
        <route>
           <leg>
            <step>...</step>
            <step>
                <start_location>
                <lat>38.9096855</lat>
                <lng>-77.0435397</lng>
                </start_location>
                <duration>
                <text>1 min</text>
                </duration>
                <distance>
                <text>39 ft</text>
                </distance>
            </step>
            <duration>
            <text>2 hours 19 mins</text>
            </duration>
            <distance>
            <text>7.1 mi</text>
            </distance>
              </leg>
        </route>
</DirectionsResponse>

这是我正在使用的Python脚本:

import urllib
from BeautifulSoup import BeautifulSoup

url = 'https://www.somexmlgenerator.com/directions/xml?somejscript'
res = urllib.urlopen(url)
html = res.read()

soup = BeautifulSoup(html)
soup.prettify()
leg = soup.findAll('leg')

for eachleg in leg:
    another_duration = eachleg('duration')
    print eachleg

正如我所提到的,我已经有一段时间了,并尝试过使用lxml,但由于XML是动态生成的,因此我很难通过它抓取XML。我采取的方法是将XML作为HTML进行抓取,但我肯定会接受其他建议,因为我还是一个新手!

1 个答案:

答案 0 :(得分:2)

使用BeautifulSoup(使用版本4,名为bs4),您需要将recursive=False传递到findAll以阻止错误持续时间:

from bs4 import BeautifulSoup

soup = BeautifulSoup(..., 'xml')

for leg in soup.route.find_all('leg', recursive=False):
    duration = leg.duration.text.strip()
    distance = leg.distance.text.strip()

或者使用CSS:

for leg in soup.select('route > leg'):
    duration = leg.duration.text.strip()
    distance = leg.distance.text.strip()

使用lxml,您只需使用XPath:

durations = root.xpath('/DirectionsResponse/route/leg/duration/text/text()')
distances = root.xpath('/DirectionsResponse/route/leg/distance/text/text()')