jsoup获得css,java - Using JSoup CSS selectors - Stack Overflow

I am trying to use JSoup to scrape some content off of a website. Here is some sample HTML content from the page I am interested in:

Fizz

Buzz

Foo

Bar

I am interested in obtaining a list of all the hotwords in the page (so "Fizz", "Buzz", "Foo" and "Bar"). But I can't just query for hotword, because they use the hotword class all over the place to decorate lots of different elements. Specifically, I need all the hotwords that exist inside a pbk pg hotword element. Note that pbks can contain 0+ pgs, and pgs can contain 0+ hotwords, and hotwords can contain 1+ other hotwords. I have the following code:

// Update, per PShemo:

Document doc = Jsoup.connect("http://somesite.example.com").get();

System.out.println("Starting to crawl...");

// Get the document's .pbk elements.

Elements pbks = doc.select(".pbk");

List hotwords = new ArrayList();

System.out.println(String.format("Found %s pbks.", pbks.size()));

int pbkCount = 0;

for(Element pbk : pbks) {

pbkCount++;

// Get the .pbk element's .pg elements.

for(Element pg : pbk.getElementsByClass("pg")) {

System.out.println(String.format("PBK #%s has %s pgs.", pbkCount, pbk.getElementsByClass("pg").size()));

Element hotword = pg.getElementById("hotword");

System.out.println("Adding hotword: " + hotword.text());

hotwords.add(hotword.text());

}

}

Running that code produces the following output:

Starting to crawl...

Found 3 pbks.

I am either not using the JSoup API correctly, or not using the right selectors, or both. Any thoughts as to where I'm going awry? Thanks in advance!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值