You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取指定XML文件返回NaN结果,求技术解决方案

解决Python读取欧洲议会MEPs XML文件返回NaN的问题

你的问题出在不必要地用BeautifulSoup处理XML内容,BeautifulSoup解析后再转成字符串会打乱原始XML的结构,导致pd.read_xml无法正确识别数据。

直接用以下两种方法就能解决:

方法1:让pandas直接读取URL(带请求头)

pd.read_xml支持直接传入URL,同时可以通过storage_options参数传递请求头:

import pandas as pd

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}
url = 'https://www.europarl.europa.eu/meps/en/full-list/xml/a'
df = pd.read_xml(url, storage_options={'headers': headers})
print(df)

方法2:用requests获取后直接传递原始内容给pandas

如果需要手动处理请求,直接把requests响应的content(字节流)传给pd.read_xml,不要经过BeautifulSoup:

import requests
import pandas as pd

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}
url = 'https://www.europarl.europa.eu/meps/en/full-list/xml/a'
response = requests.get(url, headers=headers)
df = pd.read_xml(response.content)
print(df)

这两种方法都能正确解析XML中的MEP数据,不会返回NaN。

内容的提问来源于stack exchange,提问作者Giampaolo Levorato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 00:53:11