首頁  >  文章  >  後端開發  >  如何使用 BeautifulSoup 從 Python 中的 HTML 表中擷取資料?

如何使用 BeautifulSoup 從 Python 中的 HTML 表中擷取資料?

Patricia Arquette
Patricia Arquette原創
2024-10-28 10:00:29971瀏覽

How can BeautifulSoup be used to extract data from a HTML table in Python?

BeautifulSoup解析表

在Python中,BeautifulSoup提供了強大的解析HTML文件的方法。當遇到這樣的場景,您需要從表格中檢索特定資料時,BeautifulSoup 會派上用場。

要提取目標行項目表,請使用 soup.find(),在括號中。在這種情況下,您需要:

<code class="python">table = soup.find("table", {"class": "lineItemsTable"})</code>

接下來,您可以使用 table.findAll("tr") 迭代表中的每一行。在每一行中,您可以使用 row.findAll("td") 存取表格儲存格 (td)。

這是一個增強的程式碼片段:

<code class="python">data = []
table_body = table.find('tbody')

rows = table_body.find_all('tr')
for row in rows:
    cols = row.find_all('td')
    cols = [ele.text.strip() for ele in cols]
    data.append([ele for ele in cols if ele])  # Remove empty values</code>

此程式碼將產生一個列表列表,每個子列表代表表中的一行。它將有效地從網站捕獲必要的數據。

以上是如何使用 BeautifulSoup 從 Python 中的 HTML 表中擷取資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn