从 beautifulsoup 替换 \n\t

Kyl*_*oN- 2 python replace beautifulsoup special-characters

您好,我正在使用 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)
Run Code Online (Sandbox Code Playgroud)

这是我的输出:

\n', '\t\t\t\t\t\t\t\t\t\tTEXT_I_WANT\t\t\t\t\t\t\t\t\t
Run Code Online (Sandbox Code Playgroud)

我用编码或beautifulsoup“NavigableString”尝试了几件事。我使用了错误的编码吗?或者有没有beautifulsoup的特殊方法。(例如stripped_strings)

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

ale*_*cxe 7

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

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