To find the text in a specific pair of '

' tags within HTML using Python, you can utilize the Beautiful Soup library. Here's an example:

from bs4 import BeautifulSoup

# HTML code with '<h1>' tag
html = '<html><body><h1>My Heading</h1></body></html>'

# Create a BeautifulSoup object
soup = BeautifulSoup(html, 'html.parser')

# Find the '<h1>' tag and get its text content
heading = soup.find('h1').text

# Print the heading text
print(heading)  # Output: My Heading

To find the text in the required pair of '

' tags that are located under a pair of '

' tags, you can first locate the '

' tag and then navigate to the '

' tag using the find() or find_all() method. Here's an example:

from bs4 import BeautifulSoup

# HTML code with '<p>' and '<h1>' tags
html = '<html><body><p><h1>My Heading</h1></p></body></html>'

# Create a BeautifulSoup object
soup = BeautifulSoup(html, 'html.parser')

# Find the '<p>' tag
p_tag = soup.find('p')

# Find the '<h1>' tag under the '<p>' tag and get its text content
heading = p_tag.find('h1').text

# Print the heading text
print(heading)  # Output: My Heading
Python BeautifulSoup: Extract Text from <h1> Tags & Find Headings within Paragraphs


原文地址: https://www.cveoy.top/t/topic/oslo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录