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

标签 java string jsoup element

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

基本上,我正在尝试编写一个允许用户输入单词的程序,然后该程序将转到 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/

相关文章:

java - 如何通过Java抓取CSV文件中的货币格式数字

java - 如何复用单例模式?

string - 匹配到 "::"之前的模式不适用于 string.gsub

string - 有没有收缩单词组合的软件?

C 编程查找随机字符串中的所有单词

java - Jsoup : how to extract img with space in filename?

java - 在构造函数中使用 'this' 关键字使用另一个类的一个类的方法

java - izpack 安装程序未实例化

java - 如何在 JDBCTemplates 中使用 SELECT IN 子句?

java - 想使用 Jsoup 获取 Title 和 Grade