使用BS4获取值

时间:2018-10-08 16:09:35

标签: python beautifulsoup

我正在尝试从汤中获取“数据值”,但它们都位于巨大的列表中,并且没有按照网站上显示的格式在不同的列表/列中显示。

我知道标题在这里:

<th class="num record drop-3" data-tsorter="data-val">
    <span class="long-points">
     proj. pts.
    </span>
    <span class="short-points">
     pts.
    </span>
   </th>
   <th class="pct" data-tsorter="data-val">
    <span class="full-relegated">
     relegated
    </span>
    <span class="small-relegated">
     rel.
    </span>
   </th>
   <th class="pct" data-tsorter="data-val">
    <span class="full-champ">
     qualify for UCL
    </span>
    <span class="small-champ">
     make UCL
    </span>
   </th>
   <th class="pct sorted" data-tsorter="data-val">
    <span class="drop-1">
     win Premier League
    </span>
    <span class="small-league">
     win league
    </span>
   </th>

这是我正在尝试的:

url = 'https://projects.fivethirtyeight.com/soccer-predictions/premier-league/'
r = requests.get(url = url)
soup = BeautifulSoup(r.text, "html.parser")
table = soup.find("table", {"class":"forecast-table"})
#print(table.prettify())
for i in table.find_all("td", {"class":"pct"}):
     print(i)

所以理想情况下,我希望有4个列表,其中包含类名,然后是匹配值

1 个答案:

答案 0 :(得分:2)

不确定要使用什么特定的列,但这会获得标记属性中带有data-val的所有列。

import requests
from bs4 import BeautifulSoup

url = 'https://projects.fivethirtyeight.com/soccer-predictions/premier-league/'
r = requests.get(url)

soup = BeautifulSoup(r.text, "html.parser")
table = soup.find("table", {"class": "forecast-table"})

team_rows = table.find_all("tr", {"class": "team-row"})

for team in team_rows:
    print("Team name: {}".format(team['data-str']))

    team_data = team.find_all("td")

    for data in team_data:
        if hasattr(data, 'attrs') and 'data-val' in data.attrs:
            print("\t{}".format(data.attrs['data-val']))
    print("\n")

如果我确实正确理解了您的问题,则说明您正在寻找最后两个值,这些值在html源代码中未加标签。在这种情况下,您可以尝试简单地寻找tag[6],尽管它当然不是很健壮-但是此 html解析,因此“不是很健壮”是针对课程恕我直言的。

我在这里要做的是查找所有团队行(由于类名,这很容易),然后简单地遍历团队行的{{1}中的所有td标签}。