gpt4 book ai didi

Java - 无法从元素转换为字符串

转载 作者:行者123 更新时间:2023-11-30 11:16:29 26 4
gpt4 key购买 nike

我遇到了一些问题,我已经花了很多时间尝试修复和搜索解决方案,但无济于事。所以我希望你们能够理解我想要实现的目标并提出一些建议?

基本上,我正在尝试编写一个允许用户输入单词的程序,然后该程序将转到 dictionary.reference.com,搜索单词,然后检索 .mp3 超链接(或打开它) 并允许用户听单词的发音。所以基本上它是一个单词发音程序。

我的代码还处于非常早期的阶段,但我粗略的想法是我会有一个 GUI 供他们输入单词,所以不要介意调试固定变量(例如 searchWord)。

代码如下:

import java.net.*;
import java.io.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;


public class Pronun {
String searchWord = "development"; // Fixed variable for debugging
Element audio;

public Pronun() throws Exception {
// As program is ran, begin searching the word in the dictionary.
URL makeSearch = new URL("http://dictionary.reference.com/browse/"+searchWord+"?s=t");
URLConnection connectTo = makeSearch.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connectTo.getInputStream()));

String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
File input = new File("output.txt");
Document doc = Jsoup.parse(input, "UTF-8");
Element audio = doc.select("audspk.classname").first();

// Write the hyperlink to the file "output.txt".
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt", true)));
out.println(audio);
out.close();
in.close();


}
}

我试图从页面检索的超链接是:

<a class="audspk" href="http://static.sfdict.com/dictstatic/dictionary/audio/luna/D02/D0238600.mp3">

如您所见,我正在尝试通过 Jsoup 获取它,使用它的类名 - “audspk”。

但基本上,当我运行代码时,这是我收到的错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Type mismatch: cannot convert from Elements to String

at URLConnectionReader.main(URLConnectionReader.java:25)

我已尝试通过 toString 将其转换,但这似乎也不起作用,但我一定是在那里做错了什么,因此我们将不胜感激。我希望你能理解我在这里想要实现的目标。

最佳答案

我有几点意见:

  1. 文件 output.txt 似乎是空的,因为您没有向其中写入任何内容。
  2. 如果要打印链接,请使用 Element 的方法 attr:

    String link = doc.select(".audspk").first().attr("href");
  3. jsoup可以自行下载解析URL:

    URL makeSearch = new URL("http://dictionary.reference.com/browse/" + searchWord + "?s=t");
    Document doc = Jsoup.parse(makeSearch, 1000);
    String link = doc.select(".audspk").first().attr("href");
    System.out.println(link);

关于Java - 无法从元素转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24843331/

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