用BeautifulSoup/Python从html文件中提取文本

2024-09-29 23:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个html文件中提取文本。 html文件如下所示:

<li class="toclevel-1 tocsection-1">
    <a href="#Baden-Württemberg"><span class="tocnumber">1</span>
        <span class="toctext">Baden-Württemberg</span>
    </a>
</li>
<li class="toclevel-1 tocsection-2">
    <a href="#Bayern">
        <span class="tocnumber">2</span>
        <span class="toctext">Bayern</span>
    </a>
</li>
<li class="toclevel-1 tocsection-3">
    <a href="#Berlin">
        <span class="tocnumber">3</span>
        <span class="toctext">Berlin</span>
    </a>
</li>

我想从最后一个span标记中提取最后一个文本。 第一行是“巴登-W”ürtemberg“在class="toctext"之后,然后将其放入python列表

在Python中,我尝试了以下方法:

names = soup.find_all("span",{"class":"toctext"})

我的输出是list

[<span class="toctext">Baden-Württemberg</span>, <span class="toctext">Bayern</span>, <span class="toctext">Berlin</span>]

那么我怎样才能只提取标签之间的文本呢

谢谢大家


Tags: 文件文本htmlliclasshrefspanberlin
2条回答

有了一份理解列表,你可以做到以下几点:

names = soup.find_all("span",{"class":"toctext"})
print([x.text for x in names])

find_all方法返回一个列表。遍历列表以获取文本

for name in names:
    print(name.text)

退货:

Baden-Württemberg
Bayern
Berlin

内置的python dir()type()方法总是便于检查对象

print(dir(names))

[...,
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort',
 'source']

相关问题 更多 >

    热门问题