大家好,我正在抓取一個表格并將表格的標題和正文分成單獨的串列,但正文資料有很多'/n',我正在嘗試洗掉它們,但我似乎無法將它們取出。
代碼:
soup = BeautifulSoup(driver.page_source,'html.parser')
table= soup.find("table")
rows= table.find_all("tr")
table_contents = []
for tr in rows:
if rows.index(tr)== 0:
row_cells = [ th.getText().strip() for th in tr.find_all('th') if th.getText().strip() !='']
else:
row_cells = ([ tr.find('th').getText() ] if tr.find('th') else [] ) [ td.getText().strip() for td in tr.find_all('td') if td.getText().strip() != '' ]
if len(row_cells) > 1 :
table_contents = [ row_cells ]
table_head= table_contents[0]
table_body= table_contents[1]
print (table_head)
print (table_body)
結果:
table head= ['Student Number', 'Student Name', 'Placement Date']
table body= ['20808456', 'Sandy\n(f) \nGurlow', '01/13/2023']
正如您在表格正文結果中看到的那樣,'\n' 擋住了路,我可以弄清楚如何擺脫它。因為我有 100 個樣本可以解決同樣的問題。
uj5u.com熱心網友回復:
使用str.replace()和串列理解:
[i.replace('\n', '') for i in table_body]
輸出:
['20808456', 'Sandy(f) Gurlow', '01/13/2023']
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/466209.html
