python - 使用 pandas read_html 抓取时将表行分隔为 2

标签 python pandas web-scraping beautifulsoup html-table

使用 pandas read_html() 时无法正确获取格式。我正在寻找对方法本身或底层 html(通过 bs4 抓取)的调整以获得所需的输出。

当前输出:

Current wrong output format (注意它是 1 行包含两种类型的数据。理想情况下它应该分成 2 行,如下所示)

期望:

Desired output format

复制问题的代码:

import requests
import pandas as pd
from bs4 import BeautifulSoup  # alternatively

url = "http://ufcstats.com/fight-details/bb15c0a2911043bd"

df = pd.read_html(url)[-1]  # last table
df.columns = [str(i) for i in range(len(df.columns))]

# to get the html via bs4
headers = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET",
    "Access-Control-Allow-Headers": "Content-Type",
    "Access-Control-Max-Age": "3600",
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0",
}
req = requests.get(url, headers)
soup = BeautifulSoup(req.content, "html.parser")
table_html = soup.find_all("table", {"class": "b-fight-details__table"})[-1]

最佳答案

如何(快速)修复beautifulsoup

您可以使用 table 中的标题创建一个 dict,然后遍历每个 td 以附加存储在p:

data = {}

header = [x.text.strip() for x in table_html.select('tr th')]

for i,td in enumerate(table_html.select('tr:has(td) td')):
    data[header[i]] = [x.text.strip() for x in td.select('p')]

pd.DataFrame.from_dict(data)

例子

import requests
import pandas as pd
from bs4 import BeautifulSoup  # alternatively

url = "http://ufcstats.com/fight-details/bb15c0a2911043bd"

# to get the html via bs4
headers = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET",
    "Access-Control-Allow-Headers": "Content-Type",
    "Access-Control-Max-Age": "3600",
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0",
}
req = requests.get(url, headers)
soup = BeautifulSoup(req.content, "html.parser")
table_html = soup.find_all("table", {"class": "b-fight-details__table"})[-1]

data = {}

header = [x.text.strip() for x in table_html.select('tr th')]

for i,td in enumerate(table_html.select('tr:has(td) td')):
    data[header[i]] = [x.text.strip() for x in td.select('p')]

pd.DataFrame.from_dict(data)

输出

<表类="s-表"> <头> 战斗机 签名。海峡 签名。海峡% 头部 正文 腿 距离 紧握 地面 <正文> 乔安妮·伍德 68 之 27 39% 8 of 36 3 of 7 16 of 25 67 之 26 1 of 1 0 of 0 泰拉桑托斯 30 of 60 50% 46 之 21 3 of 7 6 of 7 19 of 42 0 of 0 11 of 18

关于python - 使用 pandas read_html 抓取时将表行分隔为 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70179476/

相关文章:

python - 组合两个数据集形成 bool 列(pandas)

python - Webscraping - 不显示 html 代码的文本部分

docker 运行启动容器,但 localhost 未加载(Windows 10)

python - 如何将爬取的数据横向导出到Excel?

python - 在 Python 中使用槽和 "constants"

python - 关于Python中的time.time()

python - 平衡括号的函数

python - 如何在枕头python中制作文字阴影效果?

python - 如何计算三只股票的加权平均数

python - 无法将值列表解析为字符串列表