Вы можете перебирать свои теги, затем применять 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-документ очень большой.
Из вашего Вопроса и комментариев к предыдущему ответу, я думаю, вы пытаетесь найти
blockquote>
самые внутренние теги
, которые либо '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 <a> 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>, .... ]