Skip to main content
 首页 » 编程设计

python之为什么我只得到第一个元素

2024年11月01日798°冷暖

我正在解析 this page

我从 number2 类 中提取链接。在循环中,我遍历了 number2 的每个元素,并尝试从类 'center bold table-odds' 中获取结果。为此,我尝试找到每个链接的 parents,但问题是每次我从 first element 获得结果(在本例中是 < em>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)