gpt4 book ai didi

java - 如何使用 Jsoup 找到与某个单词匹配的所有 anchor ?

转载 作者:行者123 更新时间:2023-11-30 07:15:18 27 4
gpt4 key购买 nike

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

这是网站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);
}
}

}
}

最佳答案

问题出在这里:

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);
}

引用文献

关于java - 如何使用 Jsoup 找到与某个单词匹配的所有 anchor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38510794/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com