python - 如何从 NFL 赛程表中抓取所有 td 和 tr 数据

标签 python html web-scraping beautifulsoup

我正在从 espn.com 上抓取即将到来的 NFL 赛程的数据。但是,我只能获取表格的第一行,而不能获取表格的其余部分。我相信这是因为 html 的结构和每个日期都有不同的“td”。我可以获取周四的比赛数据,但无法获取其余数据

****9 月 5 日,星期四**** 比赛时间 (ET) NAT TV 门票地点 绿湾
芝加哥 晚上 8:20 NBC 门票低至 290 美元,芝加哥士兵场
9 月 8 日星期日 比赛时间 (ET) NAT TV 门票地点 田纳西州
克利夫兰 下午 1:00 CBS 门票低至 121 美元克利夫兰 FirstEnergy 体育场

辛辛那提
西雅图 下午 4:05 CBS 门票低至 147 美元,西雅图 CenturyLink Field
纽约
达拉斯 下午 4:25 FOX 门票低至 50 美元 阿灵顿 AT&T 体育场 福克斯伯勒 9 月 9 日星期一 比赛时间 (ET) NAT TV 门票地点 休斯顿 新奥尔良 晚上 7:10 ESPN 门票低至 112 美元 新奥尔良 Mercedes-Benz Superdome
丹佛
奥克兰 晚上 10:20 ESPN 门票低至 72 美元 奥克兰奥克兰体育馆

我使用过 beautifulsoup,很容易就能获取数据,但解析数据却遇到了挑战。

我尝试继续使用 for 循环,但我可以停止迭代回溯。在阅读了上一篇关于回溯的文章后,我意识到我需要尝试不同的解决方案来解决问题。

import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse
import pandas as pd


main_url = ['http://www.espn.com/nfl/schedule'][1]

response = requests.get(main_url)

soup = BeautifulSoup(response.text, 'lxml')

table = soup.find('table')
rows = table.find_all('tr')
rows = iter(rows)

df = [td.text for td in next(rows).find_all('td') if td.text]
df2 = [td.text for td in next(rows).find_all('td') if td.text]


[1]: https://www.espn.com/nfl/schedule

最佳答案

我认为问题出在这一行:

table = soup.find('table')

事实是,上述页面由 3 个具有 class = "schedule" 属性的 table 元素组成。但是,在您的代码中,您仅使用了 find() 函数,而不是 find_all()。这是您最终只得到第一个表的内容的主要原因。所以,我相信,如果正确处理这部分,那么你就可以顺利进行。现在,我不太熟悉用于填充列表的集合表示法,因此代码包含良好的旧 for 循环样式。

#List to store the rows 
df = []
#Collect all the tables
tables = soup.find_all('table', class_ = "schedule")
for table in tables:
    rows = soup.find_all('tr')
    #rows = iter(rows)
    row_item = []
    for row in rows:
        #Collect all 'td' elements from the 'row' & append them to a list 'row_item'
        data_items = row.find_all('td')
        for data_item in data_items: 
            row_item.append(data_item.text)
        #Append the list to the 'df'
        df.append(row_item)
        row_item = []

print(df)

关于python - 如何从 NFL 赛程表中抓取所有 td 和 tr 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56728435/

相关文章:

python - 将for循环输出写入python中的文本文件

python - 具有代理继承的 Django 模型多态性

php - 在 WordPress 中向 previous_post_links 和 next_posts_links 添加 anchor

python 网络抓取雅虎金融

python - 让网络抓取工具产生更多信息

python - 将 pandas 数据框作为数据集插入 HDFStore 中

python - 渲染时未捕获语法错误 : invalid syntax

jquery - Ajax 数据返回缓慢

javascript - 2 分钟问题 - HTML/CSS If div within div expands expand parent div

python - Google Scrape with Python 中的结果数量错误