How To Find Element Based On Text Ignore Child Tags In Beautifulsoup
I am looking for a solution using Python and BeautifulSoup to find an element based on the inside text. For example:
Ignore this textFind based on th
Solution 1:
You can use .find
with the text
argument and then use findParent
to the parent element.
Ex:
from bs4 import BeautifulSoup
s="""<div> <b>Ignore this text</b>Find based on this text </div>"""
soup = BeautifulSoup(s, 'html.parser')
t = soup.find(text="Find based on this text ")
print(t.findParent())
Output:
<div> <b>Ignore this text</b>Find based on this text </div>
Solution 2:
try it , it is like example but it works
from bs4 import BeautifulSoup
html="""
<div> <b>Ignore this text</b>Find based on this text </div>
"""
soup = BeautifulSoup(html, 'lxml')
s = soup.find('div')
for child in s.find_all('b'):
child.decompose()
print(s.get_text())
Output
Find based onthis text
Post a Comment for "How To Find Element Based On Text Ignore Child Tags In Beautifulsoup"