2

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?

Moshe Slavin
  • 4,939
  • 5
  • 21
  • 36
Alex Heebs
  • 548
  • 1
  • 5
  • 13

2 Answers2

2

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.

Lord Elrond
  • 10,935
  • 6
  • 28
  • 60
2

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"))
Moshe Slavin
  • 4,939
  • 5
  • 21
  • 36