为了账号安全,请及时绑定邮箱和手机立即绑定

在没有类的情况下在 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 关注
  • 39 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信