search
Search
Login
Map of Data Science
menu
menu
search toc
Thanks for the thanks!
close
Outline
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Extracting text that is directly under an element in Beautiful Soup

schedule Mar 5, 2023
Last updated
local_offer
PythonBeautiful Soup
Tags
tocTable of Contents
expand_more
map
Check out the interactive map of data science

To extract text that is directly under an element in Beautiful Soup use the find_all(text=True, recursive=False) method.

Consider the following HTML document:

my_html = "<div>Alex<p>Bob</p>Cathy</div>"
soup = BeautifulSoup(my_html)

To extract the all text directly under the div tag:

div_tag = soup.find("div")
div_tag.find_all(text=True, recursive=False)
['Alex', 'Cathy']

Here, note the following:

  • The text=True means to look for text instead of elements.

  • The recursive=False means to only search directly under the element. This is why the text "Bob" is not returned.

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
3
thumb_down
2
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!