2

ページhttp://sports.yahoo.com/nhl/scoreboard?d=2013-04-01からチームとすべてのスコア値 (スペースなし) を出力するコードがあります。

from bs4 import BeautifulSoup
from urllib.request import urlopen

url = urlopen("http://sports.yahoo.com/nhl/scoreboard?d=2013-04-01")

content = url.read()

soup = BeautifulSoup(content)

listnames = ''
listscores = ''

for table in soup.find_all('table', class_='scores'):
    for row in table.find_all('tr'):
        for cell in row.find_all('td', class_='yspscores'):
            if cell.text.isdigit():
                listscores += cell.text
        for cell in row.find_all('td', class_='yspscores team'):
            listnames += cell.text

print (listnames)
print (listscores)

私が解決できない問題は、Python が抽出された情報をどのように使用して、正しいチームに正しい整数値を次のような形式で与えることができるかをよく理解していないことです。

Team X: 1, 5, 11.

Web サイトの問題は、すべてのスコアが同じクラスに属していることです。すべてのテーブルが同じクラスの下にあります。唯一の違いは、href です。

4

1 に答える 1

0

値を名前に関連付けたい場合、dict通常は a が適しています。原則を示すためにコードを変更すると、次のようになります。

from bs4 import BeautifulSoup
from urllib.request import urlopen

url = urlopen('http://sports.yahoo.com/nhl/scoreboard?d=2013-04-01')

content = url.read()

soup = BeautifulSoup(content)

results = {}

for table in soup.find_all('table', class_='scores'):
    for row in table.find_all('tr'):
        scores = []
        name = None
        for cell in row.find_all('td', class_='yspscores'):
            link = cell.find('a')
            if link:
                name = link.text
            elif cell.text.isdigit():
                scores.append(cell.text)
        if name is not None:
            results[name] = scores

for name, scores in results.items():
    print('%s: %s' % (name, ', '.join(scores)))

...実行すると次の出力が得られます。

$ python3 get_scores.py
St. Louis: 1, 2, 1
San Jose: 0, 3, 0
Colorado: 0, 0, 2
Dallas: 0, 0, 0
New Jersey: 0, 1, 0
NY Islanders: 2, 0, 1
Nashville: 0, 0, 2, 0
Minnesota: 0, 1, 0
Detroit: 1, 2, 0
NY Rangers: 1, 1, 2
Anaheim: 0, 3, 1
Winnipeg: 2, 0, 0
Chicago: 1, 1, 0, 0
Calgary: 0, 0, 1
Vancouver: 0, 1, 1
Edmonton: 3, 0, 1
Montreal: 1, 1, 2
Carolina: 1, 0, 0

辞書の使用以外の重要な変更点は、追加のクラスaではなく、チームの名前を取得する要素の存在をチェックするようになったことです。teamこれは実際には文体上の選択ですが、私には、この方法でコードがより表現力豊かに見えます。

于 2013-08-16T15:25:49.367 に答える