我目前正在嘗試使用 pandas 抓取一個 html 表,并嘗試使用 BeautifulSoup,但這樣做時遇到了問題。
這是網址:https ://ciffc.net/en/ciffc/ext/member/sitrep/
由于頁面本質上是動態的,并且每天都會添加或洗掉表格,因此不能選擇使用 pd 資料框的索引。就是說,這里是以今天的表索引 7 為例,我希望從表中提取的輸出。
display(df[7].iloc[1,2])
>> 'Yukon is at a level 3 prep level - but will trend upwards with the forecasted hot and dry weather.'
我沒有這個問題,因為我可以使用 pandas.read_html 的 match 引數來抓取帶有標題的表格,但是這個表格沒有標題。表中包含的資料也非常動態,我能夠識別的唯一獨特元素是“評論”列。這是我識別此表的嘗試:
APLtable = pd.read_html(url, match='Comments')[0].head(14)
display(APLtable)
不幸的是,這沒有用,告訴我有以下錯誤
ValueError: No tables found matching pattern 'Comments'
我也嘗試過使用 BeautifulSoup 沒有成功,并且想知道是否有人會知道根據網頁的特殊性來參考該特定表格的方法。
這是有問題的html表:
</div></div><div id="section-apl" class="section-wrapper" data-title="E: Preparedness Levels"><div id="apl_table_wrapper"><table class="sticky-enabled">
<thead><tr><th class="">Agency</th><th title="Agency Preparedness Level" class=" tooltip">APL</th><th class="">Comments</th> </tr></thead>
<tbody>
<tr id="apl-table-row-0" class="odd"><td>BC</td><td>1</td><td></td> </tr>
<tr id="apl-table-row-1" class="even"><td>YT</td><td>3</td><td>Yukon is at a level 3 prep level - but will trend upwards with the forecasted hot and dry weather.</td> </tr>
<tr id="apl-table-row-2" class="odd"><td>AB</td><td>2</td><td></td> </tr>
<tr id="apl-table-row-3" class="even"><td>SK</td><td>1</td><td></td> </tr>
<tr id="apl-table-row-4" class="odd"><td>MB</td><td>1</td><td></td> </tr>
<tr id="apl-table-row-5" class="even"><td>ON</td><td>1</td><td></td> </tr>
<tr id="apl-table-row-6" class="odd"><td>QC</td><td>1</td><td></td> </tr>
<tr id="apl-table-row-7" class="even"><td>NL</td><td>2</td><td></td> </tr>
<tr id="apl-table-row-8" class="odd"><td>NB</td><td>1</td><td></td> </tr>
<tr id="apl-table-row-9" class="even"><td>NS</td><td>1</td><td></td> </tr>
<tr id="apl-table-row-10" class="odd"><td>PE</td><td>1</td><td></td> </tr>
<tr id="apl-table-row-11" class="even"><td>PC</td><td>1</td><td></td> </tr>
</tbody>
</table>
uj5u.com熱心網友回復:
恕我直言,這些表格實際上是靜態的,我會試試這個:
import requests
from bs4 import BeautifulSoup
import pandas as pd
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:101.0) Gecko/20100101 Firefox/101.0",
}
soup = (
BeautifulSoup(
requests.get(
"https://ciffc.net/en/ciffc/ext/member/sitrep/",
headers=headers,
).text,
"lxml",
).find("div", {"data-title": "E: Preparedness Levels"})
)
df = pd.read_html(str(soup), flavor="lxml")[0]
print(df)
這應該始終如一地輸出:
Agency APL Comments
0 BC 1 NaN
1 YT 3 Yukon is at a level 3 prep level - but will tr...
2 AB 2 NaN
3 SK 1 NaN
4 MB 1 NaN
5 ON 1 NaN
6 QC 1 NaN
7 NL 2 NaN
8 NB 1 NaN
9 NS 1 NaN
10 PE 1 NaN
11 PC 1 NaN
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/496236.html
上一篇:在R中抓取大象資料
