为什么我只有第一个要素?

时间:2019-10-13 22:27:52

标签: python selenium parsing selenium-webdriver

我正在解析this page

我从number2 classes中提取了链接。进一步在循环中,我遍历number2的每个元素,并尝试从类'center bold table-odds'获取结果。为此,我尝试找到每个链接的parents,但是问题是每次我从first element获得结果时(在此示例中为 31:25

<table class="table-main odds prediction-table" id="prediction-table-1">
    <tbody>

        <tr class="odd">
            <td rowspan="3" class="center status-text-won">W</td>
            <td rowspan="3" id="status-IwnElQet" class="table-time center datet t1570978800-6-1-0-0 ">Today<br>15:00</td>
            <td rowspan="3" colspan="1" class="table-participant">
                <a class="number2" href="/handball/europe/challenge-cup/vogosca-sviesa-IwnElQet/#1X2;2">1X2</a>
            </td>
            <td rowspan="3" class="center bold table-odds">31:25</td>
            <td class="center table-odds result-ok"><a href="">1.50</a></td>
        </tr>

        <tr class="even">
            <td rowspan="3" class="center status-text-lost">L</td>
            <td rowspan="3" id="status-0IZCD4u8" class="table-time center datet t1570978800-6-1-0-0 ">Today<br>15:00</td>
            <td rowspan="3" colspan="2" class="table-participant">
                <a class="number2" href="/volleyball/italy/serie-a2-women/marignano-talmassons-0IZCD4u8/#ah;2;-14.50;3">AH -14.5 Points</a>
            </td>
            <td rowspan="3" class="center bold table-odds">3:1</td>
            <td class="center table-odds result-ok"><a href="">2.01</a></td>
        </tr>

    </tbody>
</table>
odds = driver.find_elements_by_class_name('number2')

for odd in odds:   
     print(odd.get_attribute('href')) 
     print(odd.find_element_by_xpath('../..').find_element_by_class_name('center bold table-odds').text)

3 个答案:

答案 0 :(得分:1)

您的操作方式:

odds = driver.find_elements_by_class_name('number2')

for odd in odds:   
    print(odd.get_attribute('href')) 
    print(odd.find_element_by_xpath('./ancestor::tr[1]').find_element_by_css_selector('.center.bold.table-odds').text)
    # or 
    # print(odd.find_element_by_xpath('./ancestor::tr[1]//td[4]')
    # or 
    # print(odd.find_element_by_xpath('./ancestor::tr[1]//td[contains(@class,'bold')]')

第二种方式:

rows = driver.find_element_by_css_selector('#prediction-table-1 > tbody > tr')
for row in rows:   
    print(row.find_element_by_css_selector('.number2').get_attribute('href')) 
    print(row.find_element_by_css_selector('.center.bold.table-odds').text)

答案 1 :(得分:0)

您有错字

find_element_by_class_name

应该是

find_elements_by_class_name

将其全部设置为复数形式。 Read more here

答案 2 :(得分:0)

由于只有一个名称为“ number2”的类,因此只在element上进行操作,并且仅迭代一次。 赔率= driver.find_elements_by_class_name('number2')