【问题标题】:Extract only text from div tags on a page using Python and Beautiful Soup使用 Python 和 Beautiful Soup 仅从页面上的 div 标签中提取文本
【发布时间】:2016-11-24 14:39:05
【问题描述】:

我正在尝试将一个静态新闻网站作为一个项目进行抓取,我正在使用 Beautiful soup ,但我被困在一个包含 div 标签中的文本的页面上,这里的 text 表示新闻文章

该网站的链接是 http://economictimes.indiatimes.com/magazines/panache/smoking-aces-chef-irshad-qureshis-interesting-stories-related-to-celebrities/articleshow/48712333.cms

新闻文本包含在以下格式中

<html>
<body>
<div class="normal" id="foo">
      " Many "
 <a href ='/some link' target = 'blank'>Bollywood</a>
 " stars today  are avowed foodies "
 <a href = 'link2'>Ranbir Kapoor</a>
 " Alia Bhat "
</div>
</body>
</html>

我想要的文字是“今天的许多宝莱坞明星都是发誓的美食家。Alia Bhat

也就是说,无论它们在哪里,我都想要所有文本。

我能够使用 find_all('div','normal') 到达 div,但之后卡住了如何从页面中检索所有文本元素。

如果您想了解更多信息,请告诉我。

【问题讨论】:

    标签: python html css web-scraping beautifulsoup


    【解决方案1】:

    要从 beautifulsoup 中的某个元素中提取 text,您可以使用 .text 属性:

    >>> t  = """<div class="normal" id="foo">  Many  <a href ='/some link' target = 'blank'>Bollywood</a>  stars today  are avowed foodies  <a href = 'link2'>Ranbir Kapoor</a>  Alia Bhat  </div>"""
    >>> bs = BeautifulSoup(t)
    >>> print(bs.find('div').text)
      Many  Bollywood  stars today  are avowed foodies  Ranbir Kapoor  Alia Bhat
    

    【讨论】:

      猜你喜欢
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      相关资源
      最近更新 更多