【问题标题】:Associating multiple teams with multiple headers/values:将多个团队与多个标题/值相关联:
【发布时间】:2013-08-18 03:46:32
【问题描述】:

我想让你看看这个网站:

http://www.nhl.com/ice/teamstats.htm

现在,我的代码在这里。这只会打印出表格顶部的所有标题:

from bs4 import BeautifulSoup
from urllib.request import urlopen

url = urlopen("http://www.nhl.com/ice/teamstats.htm")

content = url.read()

soup = BeautifulSoup(content)

results = {}

for table in soup.find_all('table', class_='data stats'):
    for row in table.find_all('tr'):
        name = None
        for cell in row.find_all('th'):
            link = cell.find('a')
            if link:
                name = cell.a.string
                print (name)

可以肯定的是,这个东西更复杂。在很多帮助和重新学习一些被遗忘的 Python 课程的帮助下,我能够在这个网站上进行团队和分数的关联:http://sports.yahoo.com/nhl/scoreboard?d=2013-04-01

但是,前一个网页(第一个)有多个与其值相关联的标题。

我只是询问其中的一些要点,以便我可以进一步完成其余的工作而不会出现问题(或者可能是一些,谁知道)。从某种意义上说,这就是我想要完成的:

Team X: GP: 30. W: 16. L: 4, etc.

谢谢!

【问题讨论】:

    标签: python html python-3.x beautifulsoup


    【解决方案1】:

    您的代码仅处理 th。还应该处理td。

    尝试以下操作:

    from bs4 import BeautifulSoup
    from urllib.request import urlopen
    
    u = urlopen("http://www.nhl.com/ice/teamstats.htm")
    soup = BeautifulSoup(u)
    u.close()
    
    for table in soup.find_all('table', class_='data stats'):
        row = table.find('tr')
        header = []
        for cell in row.find_all('th')[1:]:
            name = cell.string.strip()
            header.append(name)
        for row in table.find_all('tr')[1:]:
            for name, cell in zip(header, row.find_all('td')[1:]):
                value = cell.string.strip()
                print('{}: {}'.format(name, value), end=', ')
            print()
    

    【讨论】:

    • 好答案。出于好奇,拉链的作用是什么?此外,[1:]。其余的很清楚。 @falsetru
    • @NathanielElder, xs[1:] 返回不带第一个元素的 xs 的副本。
    • @NathanielElder, zip(a, b) 结合a 和b 的每个元素。例如zip([1, 2, 3], [4, 5, 6]) 产生[(1,4), (2, 5), (3, 6)]。在 Python 3.x 上,产生迭代器而不是列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多