从使用Jsoup检索的文本中删除制表符

时间:2016-02-27 20:00:00

标签: java html string jsoup

我正在使用Jsoup解析HTML文件。获取h1的文本时,它还会检索表格和换行符。

'名称'我正试图从这里撤退:

In [4]: import scipy.stats

In [5]: a = numpy.random.randint(1,10,(1000,1000))

In [6]: %timeit scipy.stats.mode(a)
10 loops, best of 3: 41.6 ms per loop

In [7]: %timeit mode(a)
10 loops, best of 3: 46.7 ms per loop

In [8]: a = numpy.random.randint(1,500,(1000,1000))

In [9]: %timeit scipy.stats.mode(a)
1 loops, best of 3: 1.01 s per loop

In [10]: %timeit mode(a)
10 loops, best of 3: 80 ms per loop

In [11]: a = numpy.random.random((200,200))

In [12]: %timeit scipy.stats.mode(a)
1 loops, best of 3: 3.26 s per loop

In [13]: %timeit mode(a)
1000 loops, best of 3: 1.75 ms per loop

我试图以这种方式摆脱这些角色:

<h1>\n\t\t\tNAME\n\t\t</h1>

但这是结果:

String name = document.select( "div header > h1" ).first().ownText().replaceAll( "[^a-zA-Z]+", "" ).trim().toUpperCase(); 

如何在没有所有制表符和换行符字符的情况下获取文本?

1 个答案:

答案 0 :(得分:2)

似乎html确实包含字符串"\t""\n"。在这种情况下,您可能应该在解析之前清理源代码。这样的事情应该做:

String html = Jsoup.connect(URL).userAgent("Mozilla/5.0").execute().body();
html = html.replaceAll("\\\\[nt]", "");
Document doc = Jsoup.parse(html);