Как исключить теги из списков, которые имеют определенный тег как дочерний - PullRequest
0 голосов
/ 05 июня 2019

Я пытаюсь получить все абзацы статьи, используя BeautifulSoup, и исключаю теги абзаца, у которых вместо абзаца есть другой тег, такой как тег в них, или если у них есть тег, так как дочерний элемент получает только текстабзаца.

Это часть HTML

<div class="entry-content clearfix">
  <div class="entry-thumbnail>
  <p> In as name to here them deny wise this. As rapid woody my he me which. </p>
  <p> <a href="https://blabla"/> </p> 
  <p> Performed suspicion in certainty so frankness by attention pretended.
      Newspaper or in tolerably education enjoyment. </p>
  <p> <a href="https://blabla"/> When be draw drew ye. Defective in do recommend
      suffering. House it seven in spoil tiled court. Sister others marked 
      fat missed did out use.</p>
</div>

, и это то, что я делал до сих пор

 contents = []
 content = soup.find('div', { "class": "entry-content clearfix"}).find_all("p")
    for p in content:
        if not (p.find(findChildren("a"))):
            contents[p] = content
    if (content):
        dic['content'] = content
    else: 
        print("ARTICLE:", i, "HAS NO content")
        dic['body'] = "No content"

1 Ответ

0 голосов
/ 06 июня 2019

Используйте функцию get_text ().Он извлечет текст из абзацев.Ссылка: https://www.pythonforbeginners.com/beautifulsoup/beautifulsoup-4-python

from bs4 import BeautifulSoup
contents = """<div class="entry-content clearfix">
  <div class="entry-thumbnail>
  <p> In as name to here them deny wise this. As rapid woody my he me which. </p>
  <p> <a href="https://blabla"/> </p> 
  <p> Performed suspicion in certainty so frankness by attention pretended.
      Newspaper or in tolerably education enjoyment. </p>
  <p> <a href="https://blabla"/> When be draw drew ye. Defective in do recommend
      suffering. House it seven in spoil tiled court. Sister others marked 
      fat missed did out use.</p>
</div>"""
soup = BeautifulSoup(contents, "lxml")
print(soup.get_text()) 

Результат:

Performed suspicion in certainty so frankness by attention pretended.
      Newspaper or in tolerably education enjoyment. 
  When be draw drew ye. Defective in do recommend
      suffering. House it seven in spoil tiled court. Sister others marked 
      fat missed did out use.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...