テキスト ファイルから URL を抽出して別のテキスト ファイルに保存するだけのプログラムがあります。コードは ExtractHTML2.getURL2(url,input); を呼び出します。これは、特定のリンクの HTML コードを抽出するだけです (これは正しく機能し、そのコードをここに含める必要はありません)。
編集:コード解析ページ数、各ページで、html コードをテキスト ファイルに保存し、このテキスト ファイルを解析して、10 個のリンクを抽出します。
ここで、次のコードは、抽出された HTML コードを解析して URL を抽出することを想定しています。これは私にはうまくいきません。それは何も抽出しません。
コード編集:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.*;
public class ExtractLinks2 {
public static void getLinks2(String url, int pages) throws IOException {
{
Document doc;
Element link;
String elementLink=null;
int linkId=1; //represent the Id of the href tag inside the HTML code
//The file that contains the extracted HTML code for the web page.
File input = new File
("extracted.txt");
//To write the extracted links
FileWriter fstream = new FileWriter
("links.txt");
BufferedWriter out = new BufferedWriter(fstream);
// Loop to traverse the pages
for (int z=1; z<=pages; z++)
{
/*get the HTML code for that page and save
it in input (extracted.txt)*/
ExtractHTML2.getURL2(url, input);
//Using parse function from JSoup library
doc = Jsoup.parse(input, "UTF-8");
//Loop for 10 times to extract 10 links per page
for(int e=1; e<=10; e++)
{
link = doc.getElementById("link-"+linkId); //the href tag Id
System.out.println("This is link no."+linkId);
elementLink=link.absUrl("href");
//write the extracted link to text file
out.write(elementLink);
out.write(","); //add a comma
linkId++;
} //end for loop
linkId=1; //reset the linkId
}//end for loop
out.close();
} //end the getLinks function
} //end IOExceptions
} //end ExtractDNs class
前述のとおり、私のプログラムは URL を抽出しません。Jsoup.parse の構文に疑問があります。参照: http://jsoup.org/cookbook/input/load-document-from-file オプションの 3 番目の引数がありますが、私の場合は必要ないと思うので無視しました。HTMLページではなくテキストファイルから抽出する必要があります。
eURL =elem.text(); と入力すると、私のプログラムは href タグのテキストを抽出できます。ただし、テキストは必要ありません。URL 自体が必要です。たとえば、次の場合:
<a id="link-1" class="yschttl spt" href="/r/_ylt=A7x9QXi_UOlPrmgAYKpLBQx.;
_ylu=X3oDMTBzcG12Mm9lBHNlYwNzcgRwb3MDMTEEY29sbwNpcmQEdnRpZAM-/SIG=1329l4otf/
EXP=1340719423/**http%3a//www.which.co.uk/technology/computing/guides/how-to-buy
-the-best-laptop/" data-bk="5040.1">How to <b>buy</b> the best <b>laptop</b>
- <b>Laptop</b> <wbr />reviews - Computing ...</a>
それを行う方法があれば、「www.which.co.uk」またはさらに良い「which.co.uk」だけが必要です。
上記のプログラムが URL を抽出しない理由と、問題を修正する方法を教えてください。