【问题标题】:Change src attribute execute_script selenium python更改 src 属性 execute_script selenium python
【发布时间】:2021-09-09 09:39:26
【问题描述】:

我正在尝试应用这条线

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)

【问题讨论】:

标签: javascript python selenium


【解决方案1】:

假设stdCode是一个Python变量,你可以使用常用的方式在字符串中使用变量:

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

【讨论】:

  • 你能看看更新后的问题吗?
  • 嗯,奇怪。如果您在查询的末尾再添加一个右括号,如下所示? {sBase64}))
  • 这也不起作用。我尝试在变量之前和之后添加撇号,但这也不起作用。
猜你喜欢
  • 2012-10-09
  • 2021-02-12
  • 2013-02-24
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-02
相关资源
最近更新 更多