亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在沒有類的情況下在 BeautifulSoup 中獲取第一個(或特定的)td

在沒有類的情況下在 BeautifulSoup 中獲取第一個(或特定的)td

楊魅力 2024-01-16 10:33:37
我有一張噩夢表,沒有為 tr 和 td 標簽提供類。示例頁面如下:https ://system.gotsport.com/org_event/events/1271/schedules?age=19&gender=m(您將在下面的代碼中看到我得到了多個頁面,但這不是問題。)我想要每個括號中的團隊名稱(沒有其他名稱)。輸出應該是:OCYSFL Rush杰克遜維爾 FC亞特蘭大聯SSA邁阿密拉什 肯德爾 SCIMG坦帕灣聯等我已經能夠獲取指定表中的每個td 。但是每次嘗試[0]獲取td每一行的第一行都會給我一個“索引超出范圍”錯誤。代碼是:import requestsimport csv from bs4 import BeautifulSoupbatch_size = 2urls = ['https://system.gotsport.com/org_event/events/1271/schedules?age=19&gender=m', 'https://system.gotsport.com/org_event/events/1271/schedules?age=17&gender=m']# iterate through urlsfor url in urls:    response = requests.get(url)    soup = BeautifulSoup(response.content, "html.parser")# iterate through leagues and teams    leagues = soup.find_all('table', class_='table table-bordered table-hover table-condensed')    for league in leagues:        row = ''        rows = league.find_all('tr')        for row in rows:            team = row.find_all('td')            teamName = team[0].text.strip()                print(teamName)經過幾個小時的工作后,我覺得只需更改一個語法即可實現這一目標。是的?
查看完整描述

3 回答

?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

您可以使用 CSS 選擇器nth-of-type(n)。它適用于兩個鏈接:


import requests

from bs4 import BeautifulSoup


url = "https://system.gotsport.com/org_event/events/1271/schedules?age=19&gender=m"

soup = BeautifulSoup(requests.get(url).content, "html.parser")


for tag in soup.select(".small-margin-bottom td:nth-of-type(1)"):

    print(tag.text.strip())

輸出:


OCYS

FL Rush

Jacksonville FC

Atlanta United

SSA

...

...

Real Salt Lake U19

Real Colorado

Empire United Soccer Academy


查看完整回答
反對 回復 2024-01-16
?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

每個括號對應一個“面板”,每個面板有兩行,第一行包含比賽表中所有球隊的第一個表。


def main():


    import requests

    from bs4 import BeautifulSoup


    url = "https://system.gotsport.com/org_event/events/1271/schedules?age=19&gender=m"


    response = requests.get(url)

    response.raise_for_status()

    

    soup = BeautifulSoup(response.content, "html.parser")


    for panel in soup.find_all("div", {"class": "panel-body"}):

        for row in panel.find("tbody").find_all("tr"):

            print(row.find("td").text.strip())

    

    return 0



if __name__ == "__main__":

    import sys

    sys.exit(main())

輸出:


OCYS

FL Rush

Jacksonville FC

Atlanta United

SSA

Miami Rush Kendall SC

IMG

Tampa Bay United

Weston FC

Chargers SC

South Florida FA

Solar SC

RISE SC

...


查看完整回答
反對 回復 2024-01-16
?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

我認為問題出在表的標題上,它包含th元素而不是td元素。當您嘗試從空列表中檢索第一個元素時,它會導致范圍索引錯誤。嘗試添加長度檢查td:


for row in rows:

    team = row.find_all('td')

    if(len(team) > 0):

        teamName = team[0].text.strip()    

        print(teamName)

它應該打印出團隊名稱。


查看完整回答
反對 回復 2024-01-16
  • 3 回答
  • 0 關注
  • 205 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號