【问题标题】:Python 3 Selenium fails to execute javascriptPython 3 Selenium 无法执行 javascript
【发布时间】:2017-08-24 15:23:27
【问题描述】:

我正在使用 python 3,并且正在使用 Selenium 尝试从网站上抓取数据。我需要从列表项中删除一个类以显示我需要的数据,这是代码:

driver.execute_script("document.getElementsByClassName('otherClassName isSelected').classList.remove('isSelected');")

但我得到了错误

“selenium.common.exceptions.WebDriverException:消息:未知错误: 无法读取未定义的属性“删除”

我也试过了

driver.execute_script("document.getElementsByClassName('otherClassName isSelected').setAttribute('class', 'otherClassName')")

然后我明白了

selenium.common.exceptions.WebDriverException:消息:未知错误:document.getElementsByClassName(...).setAttribute 不是函数

【问题讨论】:

  • 您的脚本很可能是错误的,这就是 selenium 给您错误的原因。启动浏览器开发者控制台并在控制台中执行这个 JS。一旦它在那里运行,然后在 selenium 中检查它
  • 好主意,我通过这种方式发现了问题并回答了我的问题。谢谢@TarunLalwani

标签: javascript python selenium


【解决方案1】:

我猜这是因为您试图一次对 多个 元素应用类名更新,而 setAttribute() 允许同时对一个元素应用更改。

试试下面的代码

js = """document.querySelectorAll('.otherClassName.isSelected')
    .forEach( x=> x.setAttribute("class","otherClassName"));"""
driver.execute_script(js)

附:它似乎是XY problem,因为通常您在页面抓取时不需要更改页面源。您应该分享有关您最初问题的更多详细信息

【讨论】:

    【解决方案2】:

    按类获取元素后忘记加[0],所以正确的代码应该是:

    driver.execute_script("document.getElementsByClassName('otherClassName isSelected')[0].classList.remove('isSelected');")
    

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      相关资源
      最近更新 更多