使用BS4获取值

理念

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

我知道标题在这里:

<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个列表,其中包含类名和匹配值

丹妮尔(Danielle M.)

不能完全确定您想要什么特定的列,但这会data-val在标记的属性中获得所有带有a的列:

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解析,因此对于课程恕我直言,“不是很健壮”是正常的。

我在这里要做的是查找所有团队行(由于类名而已,这很容易),然后简单地循环浏览td团队行'中的所有标签tr

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章