Найдите все конечные узлы, содержащие текст, используя BeautifulSoup4 - PullRequest
0 голосов
/ 19 января 2019

Я новичок в Python и BeautifulSoup4

Я пытаюсь извлечь (только) текстовое содержимое всех тегов, которые являются 'div', 'p', 'li' и только изнепосредственный узел, а не дочерние узлы - отсюда два варианта text=True, recursive=False

Это мои попытки:

content = soup.find_all("b", "div", "p", text=True, recursive=False)

и

tags = ["div", "p", "li"]
content = soup.find_all(tags, text=True, recursive=False)

Оба из них дают мненет вывода, вы знаете, что я делаю неправильно?

РЕДАКТИРОВАТЬ - добавив больше кода и образец документа, с которым я тестирую, print(content) пусто

import requests
from bs4 import BeautifulSoup

url = "https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-list"
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})

soup = BeautifulSoup(response.text, "html.parser")

tags = ["div", "p", "li"]
content = soup.find_all(tags, text=True, recursive=False)

print(content)

Ответы [ 2 ]

0 голосов
/ 19 января 2019

Из вашего Вопроса и комментариев к предыдущему ответу, я думаю, вы пытаетесь найти

  • самые внутренние теги

  • , которыелибо 'p', либо 'li', либо 'div'

  • должны содержать текст

import requests
from bs4 import BeautifulSoup
from bs4 import NavigableString

url = "https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-list"
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})

soup = BeautifulSoup(response.text, "html.parser")
def end_node(tag):
    if tag.name not in ["div", "p", "li"]:
        return False
    if isinstance(tag,NavigableString): #if str return
        return False
    if not tag.text: #if no text return false
        return False
    elif len(tag.find_all(text=False)) > 0: #no other tags inside other than text
        return False
    return True #if valid it reaches here
content = soup.find_all(end_node)
print(content) #all end nodes matching our criteria

Образецвывод

[<p>These instructions illustrate all major features of Beautiful Soup 4,
with examples. I show you what the library is good for, how it works,
how to use it, how to make it do what you want, and what to do when it
violates your expectations.</p>, <p>The examples in this documentation should work the same way in Python
2.7 and Python 3.2.</p>, <p>This documentation has been translated into other languages by
Beautiful Soup users:</p>, <p>Here are some simple ways to navigate that data structure:</p>, <p>One common task is extracting all the URLs found within a page’s &lt;a&gt; tags:</p>, <p>Another common task is extracting all the text from a page:</p>, <p>Does this look like what you need? If so, read on.</p>, <p>If you’re using a recent version of Debian or Ubuntu Linux, you can
install Beautiful Soup with the system package manager:</p>, <p>I use Python 2.7 and Python 3.2 to develop Beautiful Soup, but it
should work with other recent versions.</p>, <p>Beautiful Soup is packaged as Python 2 code. When you install it for
use with Python 3, it’s automatically converted to Python 3 code. If
you don’t install the package, the code won’t be converted. There have
also been reports on Windows machines of the wrong version being
installed.</p>, <p>In both cases, your best bet is to completely remove the Beautiful
Soup installation from your system (including any directory created
when you unzipped the tarball) and try the installation again.</p>, <p>This table summarizes the advantages and disadvantages of each parser library:</p>, <li>Batteries included</li>, <li>Decent speed</li>, 
....
]
0 голосов
/ 19 января 2019

Вы можете перебирать теги, затем применять soup.find_all() к каждому тегу:

import requests
from bs4 import BeautifulSoup

url = "https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-list"
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})

soup = BeautifulSoup(response.text, features="lxml")

tags = ["div", "p", "li"]

for tag in tags:
    content = soup.find_all(tag, recursive=True)

    for x in content:
        print(x)

, который печатает каждый тег <div>, <p> и <li>на странице HTML.

Вы также можете установить recursive=True для рекурсивного обхода документа и извлечения всех вложенных дочерних тегов.Если вам не нужны эти вложенные дети, оставьте recursive=False.

Вместо этого вы также можете использовать lxml, что быстрее, чем html.parser.Вы можете увидеть различия в этом ответе .Это может быть полезно, если HTML-документ очень большой.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...