BeautifulSoup Table删除那些\n

2024-06-01 06:49:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一个表的内容放入一个带有代码的列表中:

soup = BeautifulSoup(html_doc,"html.parser")


for h1 in soup.find_all('h1'):
    print (h1.get_text())

for h2 in soup.find_all('h2'):
    print (h2.get_text())

restricted_webpage= soup.find( "div", {"id":"ingredients"} )
readable_restricted=str(restricted_webpage)

soup2=BeautifulSoup(readable_restricted,"html.parser")

rows=list()
for td in soup2.find_all('td'):
    rows.append(str(td.get_text()))

print(rows)

结果受到以下因素的影响\n:

^{pr2}$

HTML文档可以是found here


Tags: textinforgethtmlh2allfind
2条回答

以下内容可以解决您的问题:

map(str.strip, rows)

正如Padraic Cunningham所说,您还可以在您的td.get_text()调用中直接使用str.strip方法:

^{pr2}$

另一个使用列表理解的结果:

rows = [td.get_text().strip() for td in soup2.find_all('td')]

^{}具有内置的剥离功能:

td.get_text(strip=True)

相关问题 更多 >