我正在解析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)

最佳答案

您的操作方式:

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)

10-08 00:40