【问题标题】:Scraping player data with BeautifulSoup使用 BeautifulSoup 抓取玩家数据
【发布时间】:2021-01-22 01:08:25
【问题描述】:

我正在尝试使用 BeautifulSoup 抓取足球统计数据,并且我正在尝试从“a”标签中获取球员的姓名,但没有运气。

这是我当前的代码:

from bs4 import BeautifulSoup
import requests
import numpy as np
import pandas as pd

url = 'https://www.pro-football-reference.com/years/2020/rushing.htm#rushing_and_receiving::rush_yds'

req = requests.get(url).text
soup = BeautifulSoup(req, 'lxml')
players = []
table = soup.find('table')
rows = table.find_all('tr')
for row in rows:
    player = row.find_all('td', {'data-stat':'player'})
    print(player)

以下是返回内容的前几个示例:

[<td class="left" csk="Henry,Derrick" data-append-csv="HenrDe00" data-stat="player"><a href="/players/H/HenrDe00.htm">Derrick Henry </a>*</td>]
[<td class="left" csk="Cook,Dalvin" data-append-csv="CookDa01" data-stat="player"><a href="/players/C/CookDa01.htm">Dalvin Cook</a>*</td>]
[<td class="left" csk="Jacobs,Josh" data-append-csv="JacoJo01" data-stat="player"><a href="/players/J/JacoJo01.htm">Josh Jacobs</a>*</td>]

如何只获取文本以便获取播放器的名称?有没有比我开始的更简单的方法来做到这一点?

这是我想要的:

Derrick Henry
Dalvin Cook
Josh Jacobs

我在循环中尝试了以下操作,但出现错误:

for row in rows:
        player = row.find_all('td', {'data-stat':'player'}).text
        print(player)

谢谢!

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    在获取名称的循环中,find_all 返回一个ResultSet(这是使用选择器找到的元素的list)。你想改用find

    for row in rows:
        player = row.find('td', {'data-stat':'player'})
        if player:
            player = player.text
            print(player)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2017-10-15
      • 2015-03-27
      相关资源
      最近更新 更多