如何提取包含在 \t 和 \n 中的文本

How to extract text that is wrapped in \t and \n in selenium

我试图从一个元素中提取一些文本并在控制台中打印它,但是,文本被包裹在 \n 和 \t 中,从这个 JSON 文件中收集GET 请求。 HTML 格式如下所示:

<span class="classname ">\n\t\t\t\n \n HELLO\n \n\n

并且在检查元素 xpath 中它看起来像这样(图片因为我无法在此处复制格式):

我尝试使用 s.replace("\n\t" , "")s.strip()s.translate({ord(c): None for c in string.whitespace}) 所有这些都只是在控制台中打印了一个空白 ( )。任何帮助将不胜感激。

你可以试试:

s.xpath('normalize-space(//span[@class="classname "]/text())')

所以如果我有这样的字符串:

s = '\n\t\t\t\n \n HELLO\n \n\n'

我会使用下面的正则表达式:

\n|\t\| 

并使用 replace 然后使用 .strip() ,我会这样做:

s = '\n\t\t\t\n \n HELLO\n \n\n'

a = s.replace("\n|\t\| ", ' ').strip()
print(a)

输出:

HELLO

Process finished with exit code 0