使用Python和Beautiful Soup只从页面上的div标记提取文本

2024-09-26 22:45:57 发布

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

我试图把一个静态新闻网站作为一个项目,我正在使用美丽的汤,但我被困在一个页面,其中包含文本在div标签,这里文本意味着新闻文章

网站的链接是 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进行驱动,但是在那之后,我还是坚持了如何从页面检索所有文本元素。在

如果你想知道更多信息,请告诉我。在


Tags: 项目文本div网站html文章静态body
1条回答
网友
1楼 · 发布于 2024-09-26 22:45:57

要从beautifulGroup中的某个元素提取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

相关问题 更多 >

    热门问题