How to highlight text in complex html

Viewed 209

I have an html that looks like this:

<h3>
Heading 3
</h3>
<ol>
<li>
<ol>
....
</li>
</ol>

Need to highlight the entire html starting from first ol. I have found this solution:

soup = bs4.BeautifulSoup(open('temp.html').read(), 'lxml')
new_h1 = soup.new_tag('h1')
new_h1.string = 'Hello '
mark = soup.new_tag('mark')
mark.string = 'World'

new_h1.append(mark)

h1 = soup.h1
h1.replace_with(new_h1)
print(soup.prettify())

Is there any way to highlight entire html without having to find out the specific text?

Edit: This is what I mean by highlighted text highlighted text

Edit: I have tried this code but it only highlights the very innermost li:

for node in soup2.findAll('li'):
    if not node.string:
        continue
    value = node.string
    mark = soup2.new_tag('mark')
    mark.string = value
    node.replace_with(mark)

output

1 Answers

This will highlight all the <li> content.

As I have no clear idea of how your HTML code looks like, I have tried to highlight all the <li> content. You can modify this code to suit your requirements.

from bs4 import BeautifulSoup

with open('index.html') as f:
    soup = BeautifulSoup(f.read(), 'html.parser')

tag = soup.findAll('li')

# Highlights the <li> content
for li in tag:
    newtag = soup.new_tag('mark')
    li.string.wrap(newtag)

print(soup)

After Highlighting: https://i.stack.imgur.com/iIbXk.jpg

Related