python - 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})
该列应包含包含匹配时间的字符串。
解决方案
他们将日期时间嵌入到 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]])
推荐阅读
- java - Java在数组中获取0的值
- networking - 网络托管公司如何能够为每个人提供公共 IPv4 地址
- bash - 在tail命令中使用变量
- java - 如何使用 WebFilter 实现授权头检查
- python - 我想在会话变量的帮助下从数据库中获取值到模板
- angular - 我可以像 getter 一样返回一个函数吗?
- react-native - 反应原生阴影ios
- arrays - mongoDB 数组长度和缺失字段的总和
- r - 导入 XLS,readxl / gdata 引入 DF with NA
- node.js - 使用 express.js 中的 res 对象下载文件,然后使用 res.json 将响应发送为 true