Modify HTML with Selenium

962 Views Asked by At

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?

2

There are 2 best solutions below

0
On

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:

def highlight_element(element):
    driver_elem = element.parent

    def apply_style(s):
        driver_elem.execute_script("arguments[0].setAttribute('style', arguments[1]);",
                                   element, s)

    original_style = element.get_attribute('style')
    apply_style("background: yellow; border: 2px solid red;")
    sleep(0.5)
    apply_style(original_style)

You must pass the function an element for example:

highlight_element(driver.find_element_by_id("username"))
0
On

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.