[英]Python and Selenium To “execute_script” to solve “ElementNotVisibleException”
[英]Change src attribute execute_script selenium python
我正在嘗試應用這條線
driver.execute_script("document.querySelector('#StudentImage').setAttribute('src', 'Photos/' + stdCode + '.jpg');")
該行僅在我直接輸入 stdCode 變量的值時才有效,但是在使用變量stdCode
,出現此錯誤
JavascriptException: Message: javascript error: stdCode is not defined
(Session info: chrome=91.0.4472.114)
像那樣嘗試這些行時
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});")
我收到這個錯誤
JavascriptException: Message: javascript error: missing ) after argument list
(Session info: chrome=91.0.4472.114)
假設 stdCode 是一個 Python 變量,您可以使用在字符串中使用變量的常用方法:
driver.execute_script(f"document.querySelector('#StudentImage').setAttribute('src', 'Photos/' + {stdCode} + '.jpg');")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.