BeautifulSoup:无法访问TD内的信息

2024-09-29 01:19:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在看以下网站:

https://modules.ussquash.com/ssm/pages/leagues/League_Information.asp?leagueid=1859

我想提取每个大学的名称以及与之相关的href。对于第一个条目,我想得到Stanfordhttps://modules.ussquash.com/ssm/pages/leagues/Team_Information.asp?id=18564

我已经到了一个点,我有所有的TDs,使用BeautifulSoup。我只是很难提取学校和它的名字。你知道吗

以下是我的尝试:

def main():
    r = requests.get('https://modules.ussquash.com/ssm/pages/leagues/League_Information.asp?leagueid=1859')
    data = r.text
    soup = BeautifulSoup(data)
    table = soup.find_all('table')[1]
    rows = table.find_all('tr')[1:]
    for row in rows:
        cols = row.find_all('td')
        print(cols)

当我尝试访问cols[0]时,我得到:

IndexError: list index out of range

任何想法如何解决这将是可怕的!你知道吗

谢谢


Tags: httpscommodulesinformationtablepagesallfind
1条回答
网友
1楼 · 发布于 2024-09-29 01:19:40

前两个trthead中,没有td标记,您想跳过前两个tr:

rows = table.find_all('tr')[2:]

为了得到你想要的,我们可以简化css选择器的使用:

table = soup.find_all('table', limit=2)[1]

# skip first two tr's
rows = table.select("tr + tr + tr")
for row in rows:
    # anchor we want is inside the first td
    a = row.select_one("td a") # or  a = row.find("td").a
    print(a.text,a["href"])

而且href是一个相对路径,因此您需要将其连接到基本url:

import requests
from bs4 import BeautifulSoup
from urllib.urlparse import  urljoin

def main():
    base = "https://modules.ussquash.com/ssm/pages/leagues/"
    r = requests.get('https://modules.ussquash.com/ssm/pages/leagues/League_Information.asp?leagueid=1859')
    data = r.text
    soup = BeautifulSoup(data)

    table = soup.find_all('table', limit=2)[1]
    # skip first two tr's
    rows = table.select("tr + tr + tr")

    for row in rows:
        a = row.select_one("td a")
        print(a.text, urljoin(base, a["href"]))

相关问题 更多 >