将 \n\t 替换为 beautifulsoup

replace \n\t from beautifulsoup

您好,我正在使用 BeautifulSoup 4,我尝试替换汤文本中的“\n\t”字符。

这是我的代码:

soup = BS(html_doc, "html.parser")
for tableItem in soup.find_all("td"):
    result = str(tableItem.string)
    result = result.replace("\n\t\", "")
    print(result)

这是我的输出:

\n', '\t\t\t\t\t\t\t\t\t\tTEXT_I_WANT\t\t\t\t\t\t\t\t\t

我用编码或 beautifulsoup "NavigableString" 尝试了几种方法。我使用了错误的编码吗?或者是否有 beautifulsoup 的特殊方法。 (比如stripped_strings)

ps:我可以替换 TEXT_I_WANT 但不能替换“\n”或“\t”

此行:result = result.replace("\n\t\", "")查找 \n\t 的所有实例然后替换它们 - 它不查找 \n 或 [=18 的单个实例=] \t。看来你想要的是:

result = result.replace('\n', '')
result = result.replace('\t', '')

您实际上需要 get_text() 而不是 stringget_text() 也可以剥离,这将帮助您删除文本开头和结尾的 \n\t

soup = BS(html_doc, "html.parser")
for tableItem in soup.find_all("td"):
    print(tableItem.get_text(strip=True))