【问题标题】:BeautifulSoup: Can't Access Info Within TDBeautifulSoup:无法访问 TD 内的信息
【发布时间】:2016-10-22 01:25:52
【问题描述】:

我正在查看以下网站:

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

我已经使用 BeautifulSoup 获得了所有 TD。我只是难以提取学校及其href。

这是我的尝试:

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

任何想法如何解决这个问题都很棒!

谢谢

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    前两个tr的在没有td标签的thead中,你想跳过前两个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"]))
    

    【讨论】:

      猜你喜欢
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多