使用 pandas 時無法獲得正確的行格式read_html()。我正在尋找對方法本身或底層 html(通過 bs4 抓取)的調整以獲得所需的輸出。
電流輸出:
(注意它是包含兩種型別資料的 1 行。理想情況下,它應該被分成 2 行,如下所示)
期望:

復制問題的代碼:
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]
uj5u.com熱心網友回復:
如何(快速)修復 beautifulsoup
您可以dict使用 中的標頭創建一個,table然后遍歷每個標頭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)
輸出
| 戰斗機 | 信號。字串 | 信號。海峽 % | 頭 | 身體 | 腿 | 距離 | 成交 | 地面 |
|---|---|---|---|---|---|---|---|---|
| 喬安妮·伍德 | 68 中的 27 | 39% | 8 的 36 | 第 3 個,共 7 個 | 25 中的 16 | 67 中的 26 | 1 中的 1 | 0 的 0 |
| 泰拉·桑托斯 | 第 30 個,共 60 個 | 50% | 第 21 條,共 46 條 | 第 3 個,共 7 個 | 6 的 7 | 42 中的 19 | 0 的 0 | 11 的 18 |
uj5u.com熱心網友回復:
類似的想法使用列舉來確定行數,但使用:-soup-contains目標表,然后nth-child選擇器在串列理解期間提取相關行。pandas將結果串列轉換為 DataFrame。假設行以與當前 2 相同的模式添加。
from bs4 import BeautifulSoup as bs
import requests
import pandas as pd
r = requests.get('http://ufcstats.com/fight-details/bb15c0a2911043bd')
soup = bs(r.content, 'lxml')
table = soup.select_one(
'.js-fight-section:has(p:-soup-contains("Significant Strikes")) table')
df = pd.DataFrame(
[[i.text.strip() for i in table.select(f'tr:nth-child(1) td p:nth-child({n 1})')]
for n, _ in enumerate(table.select('tr:nth-child(1) > td:nth-child(1) > p'))], columns=[i.text.strip() for i in table.select('th')])
print(df)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/370820.html
標籤:Python 熊猫 网页抓取 美汤 html-table
