【问题标题】:How to get text?如何获取文本?
【发布时间】:2017-11-09 13:54:29
【问题描述】:

例子:

<div class=" col-md-8">
   <strong>1.</strong>&nbsp;&nbsp;&nbsp;&nbsp;Every quadratic 
   polynomial 
 can have at most
 </div>
  <div class=" col-md-
   8">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(a) If 
   b<sup>2</sup> – 4ac is a perfect square, the roots are rational.
   </div>

如何使用 find_all 方法获取仅包含强标签的 div 文本?

【问题讨论】:

  • 你尝试了什么?
  • for b in mcq.find_all('div',class_=" col-md-8")
  • 您应该包含您尝试过但在您的答案中不起作用的代码的最小版本,非常感谢它,它可以让您更轻松地帮助您。更多信息:stackoverflow.com/help/mcve
  • 澄清“仅包含强标签的div”:您是指仅包含强标签的div,还是包含强标签的div?

标签: python beautifulsoup


【解决方案1】:

通过升级你所做的一点点:

results = []
for b in mcq.find_all('div',class_=" col-md-8"): #here you find all the div of the correct class
    if b and b.find_all("strong"): # then you check if there is a "strong" tag inside 
        results.append(b) # if yes => append it to the final list

【讨论】:

  • 我看到这可能被写成多行以获得更好的可评论性,但如果使用列表理解,这可能会更加优雅。
  • 你是对的@D.Everhard,它故意(太)长了;)
【解决方案2】:

试一试。尽管我使用了您提供的内容中的类名,但它们似乎是动态生成的,因此不应依赖它们。

from bs4 import BeautifulSoup

html_content='''
<div class=" col-md-8">
        <strong>1.</strong>&nbsp;&nbsp;&nbsp;&nbsp;Every quadratic 
        polynomial 
        can have at most
    </div>
    <div class=" col-md-
        8">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(a) If 
        b<sup>2</sup> – 4ac is a perfect square, the roots are rational.
</div>
'''
soup = BeautifulSoup(html_content,"lxml")
for items in soup.find_all("div",class_="col-md-8")[0].find_all("strong"):
    core_text = ' '.join([item.strip() for item in items.next_sibling.split()])
    print(core_text)

输出:

Every quadratic polynomial can have at most

【讨论】:

    猜你喜欢
    • 2021-05-10
    • 2011-06-16
    • 2018-07-04
    • 2015-04-05
    • 2012-10-10
    • 2016-10-05
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多