Locate a text after an element in BeautifulSoup

suggest change

Imagine you have the following HTML:

<div>
    <label>Name:</label>
    John Smith
</div>

And you need to locate the text “John Smith” after the label element.

In this case, you can locate the label element by its text and then use the .next_sibling property:

from bs4 import BeautifulSoup

data = """
<div>
    <label>Name:</label>
    John Smith
</div>
"""

soup = BeautifulSoup(data, "html.parser")

label = soup.find("label", string="Name:")
print(label.next_sibling.strip())

The argument was called text before Beautiful Soup 4.4, and since 4.11 that old name emits DeprecationWarning. .next_sibling is the text node after </label>, including the newline in the sample, and strip() removes that whitespace. The intended result is John Smith. beautifulsoup4 was not installed here, so this was not re-run.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents