I want to use Selenium (running with Python 3) to modify a specific HTML element in the browser so that it has "mark" tags around it (thereby highlighting the text I am interested in). Is there a way to do this?
Modify HTML with Selenium
971 Views Asked by Alex Heebs At
2
There are 2 best solutions below
0

This is trivial to accomplish if the page is using jQuery:
driver.execute_script('$("#some_id").wrap("<mark></mark>")')
If the page isn't using jquery, you can manually add it with the following script:
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get(url)
driver.execute_script("""var jquery_script = document.createElement('script');
jquery_script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(jquery_script);""")
time.sleep(0.5) # you need to let jquery load first
driver.execute_script('$ = window.jQuery;')
driver.execute_script('$("#some_id").wrap("<mark></mark>")')
Shoutout to Furas for helping me on this one: how to add jQuery to a page using selenium.
You probably want to highlight the input box and you probably want it highlighted only for a short time...
Here is a function I use to highlight elements:
You must pass the function an element for example: