首頁 > 後端開發 > Python教學 > 如何使用 Python 的 BeautifulSoup 從表中提取特定單元格?

如何使用 Python 的 BeautifulSoup 從表中提取特定單元格?

DDD
發布: 2024-10-29 09:08:02
原創
334 人瀏覽過

How to Extract Specific Cells from a Table Using Python's BeautifulSoup?

Python BeautifulSoup 解析表

問題:

問題:

問題:
<code class="python">soup = BeautifulSoup(plateRequest.text)
table = soup.find("table", {"class": "lineItemsTable"})
for row in table.findAll("tr"):
    cells = row.findAll("td")
    print(cells)</code>
登入後複製

問題:

<code class="python">data = []
table = soup.find('table', attrs={'class':'lineItemsTable'})
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>
登入後複製
問題:相關程式碼:

[
    ['1359711259', 'SRF', '08/05/2013', '5310 4 AVE', 'K', '19', '125.00', '$'], 
    ['7086775850', 'PAS', '12/14/2013', '3908 6th Ave', 'K', '40', '125.00', '$'], 
    ['7355010165', 'OMT', '12/14/2013', '3908 6th Ave', 'K', '40', '145.00', '$'], 
    ['4002488755', 'OMT', '02/12/2014', 'NB 1ST AVE @ E 23RD ST', '5', '115.00', '$'], 
    ['7913806837', 'OMT', '03/03/2014', '5015 4th Ave', 'K', '46', '115.00', '$'], 
    ['5080015366', 'OMT', '03/10/2014', 'EB 65TH ST @ 16TH AV E', '7', '50.00', '$'], 
    ['7208770670', 'OMT', '04/08/2014', '333 15th St', 'K', '70', '65.00', '$'], 
    ['.00\n\n\nPayment Amount:']
]
登入後複製

解決方案:

要有效存取以下行和儲存格,請使用下列行修改後的程式碼:
  • 輸出:
運行修改後的程式碼將提供一個列表列表,其中每個內部列表代表表格中的一行,內部清單中的每個元素都是儲存格的文字內容:註解:輸出中的最後一行是付款金額,它不屬於表格的一部分。 每行的最後一列表示輸入文字框,可能需要特殊處理。

以上是如何使用 Python 的 BeautifulSoup 從表中提取特定單元格?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板