【问题标题】:How to find all anchors matching a word with Jsoup?如何找到与 Jsoup 匹配的所有锚点?
【发布时间】:2016-11-25 10:24:17
【问题描述】:

提前感谢您抽出宝贵时间。该代码应该连接到网站,并从包含用户输入的单词的行中抓取操作系统模型。它将搜索单词,转到该行,并在该行上为该单词刮取操作系统属性。我不明白为什么我的代码不工作,希望能得到一些帮助。

这里是网站http://www.tabletpccomparison.net/

代码如下:

import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class ExtraPart1 {
public static void main(String args[]) throws IOException{
    Scanner input = new Scanner(System.in);
    String word = "";
    System.out.println("Type in what you are trying to search for.");
    word = input.nextLine();
    System.out.println("This program will find a quality from a website for it");
    String URL = "http://www.tabletpccomparison.net/";
    Document doc = Jsoup.connect(URL).get();
    Elements elements = doc.select("a");
    for(Element e : elements){
        if(e.equals(word)){
            String next_word = e.getElementsByClass("tableJX2ope_sis").text();
            System.out.print(next_word);
        }
    }

}
}

【问题讨论】:

    标签: java html web-scraping jsoup


    【解决方案1】:

    您的CSS selector 应直接针对您尝试抓取的table 中的链接。通过仅选择 a,您将不得不迭代文档上的每个链接。

        String selector = String.format(
             "table.tableJX tr:contains(%s) > td.tableJX2ope_sis > span.field", word);
    
        for (Element os : doc.select(selector))
            System.out.println(os.ownText());
    

    【讨论】:

      【解决方案2】:

      问题出在这里:

      if(e.equals(word)){
              String next_word = e.getElementsByClass("tableJX2ope_sis").text();
              System.out.print(next_word);
      }
      

      e 是一个Element,它与String 进行比较。试试这个:

      if(e.text().equals(word)) {
         // ...
      }
      

      你可以像这样简化 for 循环:

      String cssQuery = String.format("a:containsOwn(%s)", word);
      Elements elements = doc.select(cssQuery);
      
      for(Element e : elements){
          String nextWord = e.getElementsByClass("tableJX2ope_sis").text();
          System.out.print(nextWord);
      }
      

      参考文献

      【讨论】:

        猜你喜欢
        • 2021-12-19
        • 2019-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-17
        • 1970-01-01
        • 2013-10-26
        • 1970-01-01
        相关资源
        最近更新 更多