Elements 类可以解决这个问题
我想从网站获取html内容 我使用jsoup(java开源)来crwal一个网站并使用此代码获取元素:
Document doc = Jsoup.connect("http://bj.58.com/shangdi/zufang/0/").get();
Elements hrefs = doc.select("*");
Elements hrefs2 = hrefs.select("td:lt(4)");
System.out.println(hrefs2);
我得到结果:
<td class="tc"><b class="pri">2100</b></td>
<td class="tc">ABCD</td>
<td class="tc">today</td>
或者我编辑此代码(只需在最后一行添加“text()”):
Elements hrefs2 = hrefs.select("td:lt(4)");
System.out.println(hrefs2.text());
我得到了结果:
2100 ABCD today
但我真正想要实现的是这样的结果:
2100,ABCD,today
有什么方法可以将逗号添加到结果中,以便轻松地将结果保存到带有 csv 文件的数据库中。
I want to get the html contents from a website
and I use the jsoup(java open source ) ,to crwal a web site and get the elements with this code:
Document doc = Jsoup.connect("http://bj.58.com/shangdi/zufang/0/").get();
Elements hrefs = doc.select("*");
Elements hrefs2 = hrefs.select("td:lt(4)");
System.out.println(hrefs2);
and i get the result:
<td class="tc"><b class="pri">2100</b></td>
<td class="tc">ABCD</td>
<td class="tc">today</td>
or I edit this code(just add a "text()"in the last line ) :
Elements hrefs2 = hrefs.select("td:lt(4)");
System.out.println(hrefs2.text());
and i get the result:
2100 ABCD today
but I really want to acheive is like this result:
2100,ABCD,today
is any way to add the comma into the result,so that easy to save the result into the database with csv file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我使用了 tds.append(",");
这为每个数据元素添加了一个逗号,因此它可以作为逗号分隔很好地导入
I used
tds.append(",");
this added a comma to every data element so it imported fine as comma delimited
您可以对生成的
Elements获取迭代器 > 来自
hrefs.select
,此时您可以对列表执行任何您想要的操作(即,按照您希望的方式设置其格式)。You can get an iterator over the resultant
Elements
fromhrefs.select
, and at that point you can do whatever you want with the list (i.e., format it however you wish).