Hello, World!
This is a sample paragraph.
This is another paragraph.
解决方法如下:
from bs4 import BeautifulSoup
html = '''
Hello, World!
This is a sample paragraph.
This is another paragraph.
'''
soup = BeautifulSoup(html, 'html.parser')
tag = soup.find(text="This is another paragraph.")
if tag:
print(tag.parent)
else:
print("找不到包含指定文本的标签")
完整代码示例:
from bs4 import BeautifulSoup
html = '''
Hello, World!
This is a sample paragraph.
This is another paragraph.
'''
soup = BeautifulSoup(html, 'html.parser')
tag = soup.find(text="This is another paragraph.")
if tag:
print(tag.parent)
else:
print("找不到包含指定文本的标签")
输出结果:
This is another paragraph.