首页 > 解决方案 > Pandas read_html() 在特定列上返回“nan”

问题描述

我正在使用 pandas 来抓取一个网站,但它返回一整列的'nan'值而不是正确的值。我尝试更改几个read_html()参数,例如风味、转换器和 na_values,但均未成功。我注意到问题列的 html 代码的不同之处在于其余的是'td class='type ,而没有被正确读取的则是'td data-behavior='. 当我简单地将表格复制/粘贴到 excel 中时,一切都粘贴好了。我将不胜感激任何帮助。

我尝试更改一些参数read_html()但没有成功。我也尝试使用 lxml/xpath 获取表,但也没有成功。

week_data = pd.read_html('https://www.espn.co.uk/nfl/fixtures/_/week/2/seasontype/1',
                          converters={'time': str})

该列应包含包含匹配时间的字符串。

标签: pythonpandas

解决方案


他们将日期时间嵌入到 data-date 属性中,因此另一种选择而不是求助于 selenium 只是将该属性拉出并使用 beautifulsoup 将其粘贴在 td 元素中。

from bs4 import BeautifulSoup
import requests
import pandas as pd
import dateutil
from datetime import datetime

espn_page = requests.get('https://www.espn.co.uk/nfl/fixtures/_/week/2/seasontype/1')
soup = BeautifulSoup(espn_page.content, 'html.parser')
espn_schedule = soup.find('div', {'class': 'main-content'})
for td in espn_schedule.find_all('td', {'data-behavior': 'date_time'}):
    utc = dateutil.parser.parse(td.get('data-date'))
    localtime = utc.astimezone(dateutil.tz.gettz())
    td.string = localtime.strftime("%I:%M")


df = pd.read_html(str(espn_schedule))
print(df[0].columns)
print(df[0][df[0].columns[2]])

推荐阅读