python-3.x - 如何迭代 Selenium 和 Python 中的元素?

标签 python-3.x selenium

我试图通过迭代此 HTML 的 li 列表来获取 span 标记内的文本:

<ol class="KambiBC-event-result__score-list">
    <li class="KambiBC-event-result__match">
        <span class="KambiBC-event-result__points">1</span>
        <span class="KambiBC-event-result__points">1</span>
    </li>
</ol>

但我收到错误

AttributeError: 'list' object has no attribute 'find_element_by_class_name'

在我的代码上:

meci = driver.find_elements_by_class_name('KambiBC-event-result__match')

for items in meci:

 scor = meci.find_element_by_class_name('KambiBC-event-result__points')


 print (scor.text)

最佳答案

您没有在循环内使用项目。你的循环应该是

meci = driver.find_elements_by_class_name('KambiBC-event-result__match')

for items in meci:
    scor = items.find_element_by_class_name('KambiBC-event-result__points')
    print(scor.text)

meci.find_element_by_class_name 应该是 items.find_element_by_class_name

Selenium 4 更新

正如本文中提到的Stack Overflow post ,从 Selenium 4 开始,find_element_by_* 方法已被弃用。因此,解决方案需要修改如下:

from selenium.webdriver.common.by import By

meci = driver.find_elements(By.CLASS_NAME, 'KambiBC-event-result__match')

for items in meci:
    scor = items.find_element(By.CLASS_NAME, 'KambiBC-event-result__points')
    print(scor.text)

关于python-3.x - 如何迭代 Selenium 和 Python 中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45780533/

相关文章:

python - 使用 Python 在 ESPN 的选秀前策略中重新排序球员

Python包: Get the country based on adress(non-ip)

python - 如何使用python获取列表中单个字符串中的值而不用逗号分隔csv文件中的值?

python-3.x - asyncio.coroutine 和 types.coroutine 装饰器有什么区别?

selenium - 使用 selenium webdriver 在自定义下拉列表中选择一个选项

python - 如何修复 Selenium WebDriverException : "The browser appears to have exited"

windows - Selenium 服务器 : Unexpected status SERVICE_PAUSED

macos - 在 OS X 上为 Python 3 安装 PyAudio

python - selenium无法在知乎提交答案

python - Selenium +python : Waiting on changes in style