YasserKhalil
YasserKhalil

Reputation: 9568

Change src attribute execute_script selenium python

I am trying to apply this line

driver.execute_script("document.querySelector('#StudentImage').setAttribute('src', 'Photos/' + stdCode + '.jpg');")

The line works only if I entered the value of stdCode variable directly, but when using the variable stdCode, I got this error

JavascriptException: Message: javascript error: stdCode is not defined
  (Session info: chrome=91.0.4472.114)

When trying these lines like that

sPath = 'Photos/' + stdCode + '.jpg'
with open(sPath, 'rb') as f:
    my_string = base64.b64encode(f.read())
    sBase64 = 'data:image/jpeg;base64,' + ''.join(map(chr, my_string))
    print(sBase64)
#driver.execute_script(f"document.querySelector('#StudentImage').setAttribute('src', 'Photos/' + {stdCode} + '.jpg');")
driver.execute_script(f"document.querySelector('#StudentImage').setAttribute('src', {sBase64});")

I got this error

JavascriptException: Message: javascript error: missing ) after argument list
  (Session info: chrome=91.0.4472.114)

Upvotes: 0

Views: 282

Answers (1)

IoaTzimas
IoaTzimas

Reputation: 10624

Assuming that stdCode is a Python variable, you can use the common way for using variables inside a string:

driver.execute_script(f"document.querySelector('#StudentImage').setAttribute('src', 'Photos/' + {stdCode} + '.jpg');")

Upvotes: 1

Related Questions