如何在Selenium和Python中遍历元素?

toe95027  于 2023-10-21  发布在  Python
关注(0)|答案(2)|浏览(138)

我试图通过遍历以下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>

但我得到的错误
属性错误:“list”对象没有属性“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)
mbyulnm0

mbyulnm01#

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

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中提到的,find_element_by_*方法从Selenium 4开始就被弃用了。因此,解决办法需要修改如下:

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)
plupiseo

plupiseo2#

要回答第二条注解,您需要做的就是在类名的末尾添加“:nth-child(2)”。
类“KambiBC-event-result__points”将读取“KambiBC-event-result__points:nth-child(2)”以仅访问第二个子级。

相关问题