-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathJXDocumentTest.java
403 lines (371 loc) · 21.6 KB
/
JXDocumentTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
package org.seimicrawler.xpath;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.seimicrawler.xpath.exception.XpathSyntaxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* JXDocument Tester.
*
* @author github.com/zhegexiaohuozi [email protected]
* @version 1.0
*/
@RunWith(DataProviderRunner.class)
public class JXDocumentTest {
private JXDocument underTest;
private JXDocument doubanTest;
private JXDocument custom;
private ClassLoader loader = getClass().getClassLoader();
private Logger logger = LoggerFactory.getLogger(JXDocumentTest.class);
@Before
public void before() throws Exception {
String html = "<html><body><script>console.log('aaaaa')</script><div class='test'>some body</div><div class='xiao'>Two</div></body></html>";
underTest = JXDocument.create(html);
if (doubanTest == null) {
URL t = loader.getResource("d_test.html");
assert t != null;
File dBook = new File(t.toURI());
String context = FileUtils.readFileToString(dBook, StandardCharsets.UTF_8);
doubanTest = JXDocument.create(context);
}
custom = JXDocument.create("<li><b>性别:</b>男</li>");
}
/**
* Method: sel(String xpath)
*/
@Test
public void testSel() throws Exception {
String xpath = "//script[1]/text()";
JXNode res = underTest.selNOne(xpath);
Assert.assertNotNull(res);
Assert.assertEquals("console.log('aaaaa')",res.asString());
}
@Test
public void testNotMatchFilter() throws Exception {
String xpath = "//div[contains(@class,'xiao')]/text()";
JXNode node = underTest.selNOne(xpath);
Assert.assertEquals("Two",node.asString());
}
@Test
@DataProvider(value = {
"//a/@href",
"//div[@class='paginator']/span[@class='next']/a/@href",
})
public void testXpath(String xpath) throws XpathSyntaxErrorException {
logger.info("current xpath: {}" , xpath);
List<JXNode> rs = doubanTest.selN(xpath);
for (JXNode n : rs) {
if (!n.isString()) {
int index = n.asElement().siblingIndex();
logger.info("index = {}",index);
}
logger.info(n.toString());
}
}
/**
* d_test.html 来源于 https://book.douban.com/tag/%E4%BA%92%E8%81%94%E7%BD%91
*
* 为了测试各种可能情况,ul[@class='subject-list']节点以及其下内容被复制了一份出来,并修改部分书名前缀为'T2-'以便区分
*/
@DataProvider
public static Object[][] dataOfXpathAndexpect() {
return new Object[][] {
{ "//ul[@class='subject-list']/li[position()<3][last()]/div/h2/allText()", "黑客与画家 : 硅谷创业之父Paul Graham文集T2-黑客与画家 : 硅谷创业之父Paul Graham文集" },
{ "//ul[@class='subject-list']/li[2]/div/h2//text()", "黑客与画家: 硅谷创业之父Paul Graham文集T2-黑客与画家: 硅谷创业之父Paul Graham文集" },
{ "//ul[@class='subject-list']/li[first()]/div/h2/allText()", "失控 : 全人类的最终命运和结局T2-失控 : 全人类的最终命运和结局" },
{ "//ul[@class='subject-list']/li[./div/div/span[@class='pl']/num()>(1000+90*(2*50))][last()][1]/div/h2/allText()", "长尾理论长尾理论" },
{ "//ul[@class='subject-list']/li[self::li/div/div/span[@class='pl']/num()>10000][-1]/div/h2/allText()", "长尾理论长尾理论" },
{ "//ul[@class='subject-list']/li[contains(self::li/div/div/span[@class='pl']//text(),'14582')]/div/h2//text()", "黑客与画家: 硅谷创业之父Paul Graham文集T2-黑客与画家: 硅谷创业之父Paul Graham文集" },
{ "//ul[@class='subject-list']/li[contains(./div/div/span[@class='pl']//text(),'14582')]/div/h2//text()", "黑客与画家: 硅谷创业之父Paul Graham文集T2-黑客与画家: 硅谷创业之父Paul Graham文集" },
{ "//*[@id=\"subject_list\"]/ul/li[2]/div[2]/h2/a//text()", "黑客与画家: 硅谷创业之父Paul Graham文集T2-黑客与画家: 硅谷创业之父Paul Graham文集" },
{ "//ul[@class]", 3L },
{ "//a[@id]/@href", "https://www.douban.com/doumail/" },
{ "//*[@id='subject_list']/ul[1]/li[8]/div[2]/div[2]/span[3]/num()", "3734" },
{ "//a[@id]/@href | //*[@id='subject_list']/ul[1]/li[8]/div[2]/div[2]/span[3]/num()", "https://www.douban.com/doumail/3734" },
};
}
@UseDataProvider("dataOfXpathAndexpect")
@Test
public void testXpathAndAssert(String xpath,Object expect) throws XpathSyntaxErrorException {
logger.info("current xpath: {}" , xpath);
List<JXNode> rs = doubanTest.selN(xpath);
if (expect instanceof String){
String res = StringUtils.join(rs,"");
logger.info(res);
Assert.assertEquals(expect,res);
}else if (expect instanceof Number){
long size = (long) expect;
Assert.assertEquals(size,rs.size());
}
}
@Test
@DataProvider(value = {
"//ul[@class='subject-list']/li[position()<3]"
})
public void testJXNode(String xpath) throws XpathSyntaxErrorException {
logger.info("current xpath: {}" , xpath);
List<JXNode> jxNodeList = doubanTest.selN(xpath);
Set<String> expect = new HashSet<>();
//第一个 ul 中的
expect.add("失控: 全人类的最终命运和结局");
expect.add("黑客与画家: 硅谷创业之父Paul Graham文集");
//第二个 ul 中的
expect.add("T2-失控: 全人类的最终命运和结局");
expect.add("T2-黑客与画家: 硅谷创业之父Paul Graham文集");
Set<String> res = new HashSet<>();
for (JXNode node : jxNodeList) {
if (!node.isString()) {
String currentRes = StringUtils.join(node.sel("/div/h2/a//text()"), "");
logger.info(currentRes);
res.add(currentRes);
}
}
Assert.assertEquals(expect, res);
}
@Test
@DataProvider(value = {
"//ul[@class='subject-list']"
})
public void testRecursionNode(String xpath) throws XpathSyntaxErrorException {
logger.info("current xpath: {}" , xpath);
List<JXNode> jxNodeList = doubanTest.selN(xpath);
logger.info("size = {}",jxNodeList.size());
// 有两个ul,下面的是为了测试特意复制添加的
Assert.assertEquals(2, jxNodeList.size());
}
@Test
@DataProvider(value = {
"//body/div/div/h1/text()",
"/body/div/div/h1/text()"
})
public void absolutePathTest(String xpath) throws XpathSyntaxErrorException {
logger.info("current xpath: {}" , xpath);
List<JXNode> jxNodeList = doubanTest.selN(xpath);
logger.info("size = {},res ={}",jxNodeList.size(),jxNodeList);
}
@Test
public void testAs() throws XpathSyntaxErrorException {
List<JXNode> jxNodeList = custom.selN("//b[contains(text(),'性别')]/parent::*/text()");
Assert.assertEquals("男",StringUtils.join(jxNodeList,""));
for (JXNode jxNode : jxNodeList) {
logger.info(jxNode.toString());
}
}
/**
* fix https://github.com/zhegexiaohuozi/JsoupXpath/issues/33
*/
// @Test
public void testNotObj(){
JXDocument doc = JXDocument.createByUrl("https://www.gxwztv.com/61/61514/");
// List<JXNode> nodes = doc.selN("//*[@id=\"chapters-list\"]/li[@style]");
List<JXNode> nodes = doc.selN("//*[@id=\"chapters-list\"]/li[not(@style)]");
for (JXNode node:nodes){
logger.info("r = {}",node);
}
}
/**
* fix https://github.com/zhegexiaohuozi/JsoupXpath/issues/34
*/
@Test
public void testAttrAtRoot(){
String content = "<html>\n" +
" <head></head>\n" +
" <body>\n" +
" <a href=\"/124/124818/162585930.html\">第2章 神奇交流群</a>\n" +
" </body>\n" +
"</html>";
JXDocument doc = JXDocument.create(content);
List<JXNode> nodes = doc.selN("//@href");
for (JXNode node:nodes){
logger.info("r = {}",node);
}
}
@Test
public void testA(){
String content = "<span style=\"color: #5191ce;\" >网页设计师</span>";
JXDocument doc = JXDocument.create(content);
List<JXNode> nodes = doc.selN("//*[text()='网页设计师']");
for (JXNode node:nodes){
logger.info("r = {}",node);
}
}
/**
* fix https://github.com/zhegexiaohuozi/JsoupXpath/issues/52
*/
@Test
public void fixTextBehaviorTest(){
String html = "<p><span class=\"text-muted\">分类:</span>动漫<span class=\"split-line\"></span><span class=\"text-muted hidden-xs\">地区:</span>日本<span class=\"split-line\"></span><span class=\"text-muted hidden-xs\">年份:</span>2010</p>";
JXDocument jxDocument = JXDocument.create(html);
List<JXNode> jxNodes = jxDocument.selN("//text()[3]");
String actual = StringUtils.join(jxNodes,"");
logger.info("actual = {}",actual);
Assert.assertEquals("2010", actual);
List<JXNode> nodes = jxDocument.selN("//text()");
String allText = StringUtils.join(nodes,"");
Assert.assertEquals("分类:动漫地区:日本年份:2010",allText);
logger.info("all = {}",allText);
}
/**
* fix https://github.com/zhegexiaohuozi/JsoupXpath/issues/44
*/
@Test
public void fixTextElNoParentTest(){
String test="<div class='a'> a <div>need</div> <div class='e'> not need</div> c </div>";
JXDocument j = JXDocument.create(test);
List<JXNode> l = j.selN("//div[@class='a']//text()[not(ancestor::div[@class='e'])]");
Set<String> finalRes = new HashSet<>();
for (JXNode i : l){
logger.info("{}",i.toString());
finalRes.add(i.asString());
}
Assert.assertFalse(finalRes.contains("not need"));
Assert.assertTrue(finalRes.contains("need"));
Assert.assertEquals(4, finalRes.size());
}
/**
* fix https://github.com/zhegexiaohuozi/JsoupXpath/issues/53
*/
@Test
public void fixIssue53(){
String content = "<li class=\"res-book-item\" data-bid=\"1018351389\" data-rid=\"1\"> \n" +
" <div class=\"book-img-box\"> <a href=\"//book.qidian.com/info/1018351389\" target=\"_blank\" data-eid=\"qd_S04\" data-algrid=\"0.0.0\" data-bid=\"1018351389\"><img src=\"//bookcover.yuewen.com/qdbimg/349573/1018351389/150\"></a> \n" +
" </div> \n" +
" <div class=\"book-mid-info\"> \n" +
" <h4><a href=\"//book.qidian.com/info/1018351389\" target=\"_blank\" data-eid=\"qd_S05\" data-bid=\"1018351389\" data-algrid=\"0.0.0\"><cite class=\"red-kw\">我们</cite>平凡<cite class=\"red-kw\">我们</cite>忠诚</a></h4> \n" +
" <p class=\"author\"> <img src=\"//qidian.gtimg.com/qd/images/ico/user.f22d3.png\"><a class=\"name\" data-eid=\"qd_S06\" href=\"//my.qidian.com/author/403791004\" target=\"_blank\">巡璃</a> <em>|</em><a href=\"//www.qidian.com/duanpian\" data-eid=\"qd_S07\" target=\"_blank\">短篇</a><em>|</em><span>连载</span> </p> \n" +
" <p class=\"intro\"> 这是一位普通老兵的故事,这位老兵没有走上战场,也没有人歌颂他,但他的工作却是面对生与死,他是一名普通的军转干部,没有得到任何荣誉,却仍旧坚守着信仰,永远忠诚。除了他的家人,他的战友,他的故事不被任何人所知,但他的故事正是一代军人、一代军转干部的写照。所以,我来歌颂他,歌颂那一代人。 </p> \n" +
" <p class=\"update\"><a href=\"//read.qidian.com/chapter/YiObT_DmJpXu4xLcYRGW6w2/Ulsr6ThvJS5p4rPq4Fd4KQ2\" target=\"_blank\" data-eid=\"qd_S08\" data-bid=\"1018351389\" data-cid=\"//read.qidian.com/chapter/YiObT_DmJpXu4xLcYRGW6w2/Ulsr6ThvJS5p4rPq4Fd4KQ2\">最新更新 第一次见识到生死</a><em>·</em><span>2020-02-19</span> </p> \n" +
" </div> \n" +
" <div class=\"book-right-info\"> \n" +
" <div class=\"total\"> \n" +
" <p><span> 4497</span>总字数</p> \n" +
" <p><span> 0</span>总推荐</p> \n" +
" </div> \n" +
" <p class=\"btn\"> <a class=\"red-btn\" href=\"//book.qidian.com/info/1018351389\" data-eid=\"qd_S02\" target=\"_blank\">书籍详情</a> <a class=\"blue-btn add-book\" href=\"javascript:\" data-eid=\"qd_S03\" data-bookid=\"1018351389\" data-bid=\"1018351389\">加入书架</a> </p> \n" +
" </div> </li>";
JXDocument j = JXDocument.create(content);
List<JXNode> l = j.selN("//*[text()='总字数']//text()");
Assert.assertEquals(2,l.size());
Assert.assertEquals("4497",l.get(0).asString());
Assert.assertEquals("总字数",l.get(1).asString());
}
@Test
public void fixIssue53B(){
String content = "<li class=\"res-book-item\" data-bid=\"1018351389\" data-rid=\"1\"> \n" +
" <div class=\"book-img-box\"> <a href=\"//book.qidian.com/info/1018351389\" target=\"_blank\" data-eid=\"qd_S04\" data-algrid=\"0.0.0\" data-bid=\"1018351389\"><img src=\"//bookcover.yuewen.com/qdbimg/349573/1018351389/150\"></a> \n" +
" </div> \n" +
" <div class=\"book-mid-info\"> \n" +
" <h4><a href=\"//book.qidian.com/info/1018351389\" target=\"_blank\" data-eid=\"qd_S05\" data-bid=\"1018351389\" data-algrid=\"0.0.0\"><cite class=\"red-kw\">我们</cite>平凡<cite class=\"red-kw\">我们</cite>忠诚</a></h4> \n" +
" <p class=\"author\"> <img src=\"//qidian.gtimg.com/qd/images/ico/user.f22d3.png\"><a class=\"name\" data-eid=\"qd_S06\" href=\"//my.qidian.com/author/403791004\" target=\"_blank\">巡璃</a> <em>|</em><a href=\"//www.qidian.com/duanpian\" data-eid=\"qd_S07\" target=\"_blank\">短篇</a><em>|</em><span>连载</span> </p> \n" +
" <p class=\"intro\"> 这是一位普通老兵的故事,这位老兵没有走上战场,也没有人歌颂他,但他的工作却是面对生与死,他是一名普通的军转干部,没有得到任何荣誉,却仍旧坚守着信仰,永远忠诚。除了他的家人,他的战友,他的故事不被任何人所知,但他的故事正是一代军人、一代军转干部的写照。所以,我来歌颂他,歌颂那一代人。 </p> \n" +
" <p class=\"update\"><a href=\"//read.qidian.com/chapter/YiObT_DmJpXu4xLcYRGW6w2/Ulsr6ThvJS5p4rPq4Fd4KQ2\" target=\"_blank\" data-eid=\"qd_S08\" data-bid=\"1018351389\" data-cid=\"//read.qidian.com/chapter/YiObT_DmJpXu4xLcYRGW6w2/Ulsr6ThvJS5p4rPq4Fd4KQ2\">最新更新 第一次见识到生死</a><em>·</em><span>2020-02-19</span> </p> \n" +
" </div> \n" +
" <div class=\"book-right-info\"> \n" +
" <div class=\"total\"> \n" +
" <p><span> 4497</span>总字数</p> \n" +
" <p><span> 0</span>总推荐</p> \n" +
" </div> \n" +
" <p class=\"btn\"> <a class=\"red-btn\" href=\"//book.qidian.com/info/1018351389\" data-eid=\"qd_S02\" target=\"_blank\">书籍详情</a> <a class=\"blue-btn add-book\" href=\"javascript:\" data-eid=\"qd_S03\" data-bookid=\"1018351389\" data-bid=\"1018351389\">加入书架</a> </p> \n" +
" </div> </li>";
JXDocument j = JXDocument.create(content);
List<JXNode> l = j.selN("//*[text()='总字数']//text()[1]");
logger.info("{}",l);
Assert.assertEquals(2, l.size());
// xpath索引值从1开始
List<JXNode> l2 = j.selN("//*[text()='总字数']//text()[0]");
Assert.assertEquals(0,l2.size());
List<JXNode> l3 = j.selN("//*[text()='总字数']//text()[2]");
Assert.assertEquals(0,l3.size());
}
@Test
public void textChildOrderTest(){
String content = "<p> one <span> two</span> three </p>";
JXDocument j = JXDocument.create(content);
Assert.assertEquals(StringUtils.join(j.selN("//text()[2]"),""), "three");
}
@Test
public void issue64And65(){
String content = "<div class='a'>1</div>" +
"<div>2</div>\n" +
"<div class='a'>3</div>\n" +
"<div>4</div>\n" +
"<div>5</div>11" +
"<tag>6</tag>12" +
"<div>7<span>8</span></div>" +
"";
JXDocument j = JXDocument.create(content);
Assert.assertEquals("2", j.selNOne("//div[text()='3']/preceding-sibling-one::div/text()").asString());
Assert.assertEquals("4", j.selNOne("//div[text()='3']/following-sibling-one::div/text()").asString());
Assert.assertEquals("7", j.selNOne("//div[text()='5']/following-sibling::div/text()").asString());
Assert.assertEquals("6", j.selNOne("//div[text()='5']/following-sibling::tag/text()").asString());
Assert.assertEquals("11", j.selNOne("//div[text()='5']/following-sibling::text()").asString());
Assert.assertEquals("12", j.selNOne("//div[text()='7']/preceding-sibling::text()").asString());
Assert.assertEquals("5", j.selNOne("//div[text()='7']/preceding-sibling::div/text()").asString());
Assert.assertEquals("6", j.selNOne("//div[text()='7']/preceding-sibling::tag/text()").asString());
Assert.assertEquals("6", j.selNOne("//div[text()='7']/preceding-sibling::tag/text()").asString());
Assert.assertEquals("11 6 12 7 8", j.selN("//div[text()='5']/following::text()").stream().map(Objects::toString).collect(Collectors.joining(" ")).trim());
Assert.assertEquals("6", j.selN("//div[text()='5']/following::tag/text()").stream().map(Objects::toString).collect(Collectors.joining(" ")).trim());
Assert.assertEquals("8", j.selN("//div[text()='5']/following::span/text()").stream().map(Objects::toString).collect(Collectors.joining(" ")).trim());
Assert.assertEquals("5 7", j.selN("//div[text()='4']/following::div/text()").stream().map(Objects::toString).collect(Collectors.joining(" ")).trim());
Assert.assertEquals("2 1", j.selN("//div[text()='3']/preceding::text()").stream().map(Objects::toString).collect(Collectors.joining(" ")).trim());
Assert.assertEquals("3 2 1", j.selN("//div[text()='4']/preceding::text()").stream().map(Objects::toString).collect(Collectors.joining(" ")).trim());
}
@Test
public void issue66() throws Exception {
JXDocument j = createFromResource("issue66.html");
logger.info("{}", j.selN("count(//bookstore/book)"));
logger.info("{}", j.selN("sum(//bookstore/book/year[num()<2005])"));
logger.info("{}", j.selN("sum(//bookstore/book/price)"));
logger.info("{}", j.selN("sum(//bookstore/book/title)"));
Assert.assertEquals(4,j.selNOne("count(//bookstore/book)").asLong().longValue());
Assert.assertEquals("30.00 29.99 49.99",j.selN("//bookstore/book[position()<count(//bookstore/book)]/price/text()").stream().map(Objects::toString).collect(Collectors.joining(" ")).trim());
Assert.assertEquals("30.00 29.99",j.selN("//bookstore/book[position()<count(//bookstore/book)-1]/price/text()").stream().map(Objects::toString).collect(Collectors.joining(" ")).trim());
Assert.assertEquals(4006,j.selNOne("sum(//bookstore/book/year[num()<2005])").asLong().longValue());
Assert.assertEquals("",j.selNOne("sum(//bookstore/book/title)").asString());
}
@Test
public void i42() throws Exception {
JXDocument j = createFromResource("issue66.html");
logger.info("{}", j.selNOne("//bookstore/book[last()]/price"));
Assert.assertEquals(39.95, j.selNOne("//bookstore/book[last()]/price/num()").asDouble().doubleValue(),10);
}
@Test
public void testDoubanDetailInfoExtra() throws Exception{
JXDocument doc = createFromResource("d_detail_page.html");
JXNode score = doc.selNOne("//*[@id=\"interest_sectl\"]/div/div[2]/strong/text()");
logger.info("{}", score.asString());
JXNode title = doc.selNOne("//*[@id=\"wrapper\"]/h1/span/text()");
logger.info("{}", title.asString());
JXNode pageNum = doc.selNOne("//*[@id=\"info\"]/span[contains(text(),'页数')]/following-sibling::text()");
logger.info("{}", pageNum.asString());
Assert.assertEquals("956", pageNum.asString());
JXNode price = doc.selNOne("//*[@id=\"info\"]/span[contains(text(),'定价')]/following-sibling::text()");
logger.info("{}", price.asString());
Assert.assertEquals("139.00元", price.asString());
}
private JXDocument createFromResource(String fileName){
JXDocument jxDocument = null;
try {
jxDocument = JXDocument.create(FileUtils.readFileToString(new File(loader.getResource(fileName).toURI()), StandardCharsets.UTF_8));
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
assert jxDocument!=null;
return jxDocument;
}
}