【问题标题】:Python : how to get the text in <li> using BeautifulSoupPython:如何使用 BeautifulSoup 获取 <li> 中的文本
【发布时间】:2016-03-28 12:51:22
【问题描述】:

这是我要处理的 html 文件:

<ul class="canTouch" data-com="hrefTo,href:'/movie/246286?_v_=yes'">
    <li class='c1'>
        <b>Important text</b>
        <br><em>useless text </em><em style="margin-left: .1rem">useless text</em>
    </li>
    <li class="c2 ">
        <b>938.6</b><br/>
    </li>
    <li class="c3 ">19.7%</li>
    <li class="c4 ">19.6%</li>
    <li class="c5 ">
        <span style="margin-right:-.1rem">8.6%</span>
        <span style="padding-right:.24rem" class="_more"></span>
    </li>
</ul>

文件中有很多ul标签,这是我的代码:

for ul in soup.find_all('ul')[3:]:
lis=ul.find_all('li')
for elem in lis:
    records.append(elem.text.strip())

我不想要liem 标记中的无用文本,但我需要b 标记中的重要文本:

<li class='c1'>
    <b>Important text</b>
    <br><em>useless text<em style="margin-left: .1rem">useless text</em>
 </li>

我该怎么办?

【问题讨论】:

  • 你想只从第一个li标签还是所有li标签中抓取数据?

标签: python html beautifulsoup html-parsing


【解决方案1】:

更改将是微不足道的,替换:

records.append(elem.text.strip())

与:

records.append(elem.b.text.strip())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    相关资源
    最近更新 更多