Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3 Selenium无法执行javascript_Javascript_Python_Selenium - Fatal编程技术网

Python 3 Selenium无法执行javascript

Python 3 Selenium无法执行javascript,javascript,python,selenium,Javascript,Python,Selenium,我正在使用Python3,我正在使用Selenium尝试从网站上刮取数据。我需要从列表项中删除一个类以显示我需要的数据,代码如下: driver.execute_script("document.getElementsByClassName('otherClassName isSelected').classList.remove('isSelected');") 但是我得到了错误 “selenium.common.exceptions.WebDriverException:消息:未知错误:

我正在使用Python3,我正在使用Selenium尝试从网站上刮取数据。我需要从列表项中删除一个类以显示我需要的数据,代码如下:

driver.execute_script("document.getElementsByClassName('otherClassName isSelected').classList.remove('isSelected');")
但是我得到了错误

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

我也试过了

driver.execute_script("document.getElementsByClassName('otherClassName isSelected').setAttribute('class', 'otherClassName')")
但是我得到了

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


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

请尝试下面的代码

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

另外,在抓取页面时,您似乎通常不需要对页面源代码进行更改。您应该分享有关初始问题的更多详细信息

在按类获取元素后,我忘记添加[0],因此正确的代码应该是:

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

您的脚本很可能是错误的,这就是为什么selenium会给您一个错误。启动browser developer控制台并在控制台中执行此JS。一旦它运行到那里,然后在seleniumGood idea中检查它,我就这样发现了问题并回答了我的问题。谢谢你@TarunLalwani