【问题标题】:Scraping XML with Python module BeautifulSoup, need a specific tag in the tree使用 Python 模块 BeautifulSoup 抓取 XML,需要树中的特定标签
【发布时间】:2014-04-12 18:43:45
【问题描述】:

所以我已经在这个 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 的方法,但我绝对愿意接受其他建议,因为我还是个新手!

【问题讨论】:

    标签: python html xml beautifulsoup lxml


    【解决方案1】:

    使用 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()')
    

    【讨论】:

    • 这可能是一个新手问题,但我已经在 python 版本 2.7.3 上安装了 BS4,我还安装了 beautifulsoup3,所以我想知道这是否是我不能调用 BS4 的原因,因为它没有一个漂亮的汤文件,因为那是在 BS3 中?
    • @Logan:它们是完全独立的包,所以你可以同时安装。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 2021-06-05
    相关资源
    最近更新 更多