首页 > 解决方案 > 使用 python 在 selenium 中修改 div 的类

问题描述

我正在尝试将网页的页面布局从网格列表更改为简单列表,但问题不是下拉列表或按钮。它正在改变向 div 元素添加活动类我如何在 python 中使用 selenium 来实现这一点

<a href="#" class="dropdown-item title_mode active" id="0"><span class="fas fa-th-large fa-fw " aria-hidden="true"></span> Detailed</a>
<a href="#" class="dropdown-item title_mode " id="1"><span class="fas fa-th-large fa-fw " aria-hidden="true"></span> grid Detailed</a>
<a href="#" class="dropdown-item title_mode " id="2"><span class="fas fa-th-large fa-fw " aria-hidden="true"></span>list  Detailed</a>
<a href="#" class="dropdown-item title_mode " id="3"><span class="fas fa-th-large fa-fw " aria-hidden="true"></span>simple Detailed</a>

标签: pythonhtmlpython-3.xselenium

解决方案


您可以尝试driver.execute_script使用 Javascript 修改类的功能。像这样的东西:

driver.execute_script("""
document.getElementById('0').classList.remove('active');
document.getElementById('1').classList.add('active');
""")

根据网站的设置方式,仅修改类可能不起作用。

奇怪的是,我找不到该函数的任何文档可供参考,但它在 selenium-python 文档的常见问题解答中有所提及


推荐阅读