私は、あなたが欲しい曲をグーグルで検索し、その歌詞を印刷できる小さなプログラムをやっています。この目的のために、JavaでHTMLUnitを使用しています。ターゲット テキストを検索してから、最初の Google の結果をクリックします。しかし、ブラウザから結果を確認すると、ページが異なります。
おそらく私の間違いは XPath によるものですが、よくわかりません。というのは、Google Chrome の XPATH ビューアーと 2 つの Firefox 拡張機能の両方を使用したからです。
クロムでは、XPATH を表示する要素を右クリックしてから、下部のウィンドウからアンカー () を右クリックします。次に、[XPath をコピー] を選択します。次に、適切な「s」を「」に変更します。
これまでの私のソースコードは次のとおりです。今のところランダムな曲を書きました。
どうもありがとうございました。
ソースコード:
(私はたくさんのものを試しました。ソースコードが乱雑で申し訳ありません。これまでに試したことを示すために行を消去しませんでした。ありがとうございました。)
import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class dsa {
public static void main(String args[]) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
webClient.setThrowExceptionOnScriptError(false);
//webClient.setJavaScriptEnabled(false);
String address = "http://www.google.com/search?q=";
String searchString = "Metallica - Whiskey In The Jar";
//String searchString = "testtesttest";
String someString = address.concat(searchString);
String lastString = someString.concat(" site:randomlyricswebpageblabla.com");
// site:anotherrandomlyricswebpage.com
HtmlPage currentPage = webClient.getPage(lastString);
/*
HtmlTextInput searchBox = (HtmlTextInput) currentPage.getElementById("search_input");
searchBox.setTextContent("Amorphis - From The Heaven Of My Heart");
HtmlButtonInput button = (HtmlButtonInput) currentPage.getElementById("search_button");
HtmlPage newPage = button.click();
*/
//System.out.println(currentPage.asText());
//
//
//HtmlElement element = (HtmlElement)currentPage.getByXPath("//h3").get(0);
//DomNode result = element.getChildNodes().get(0);
//HtmlAnchor hede = (HtmlAnchor) element.getFirstChild();
//HtmlPage newPage = hede.click();
//HtmlElement firstGoogleResult = (HtmlElement) currentPage.getByXPath("//*[@id='rso']/li[1]/div/h3/a").get(0);
//HtmlAnchor testAnchor = (HtmlAnchor) firstGoogleResult.getFirstChild();
HtmlAnchor firstGoogleResult = (HtmlAnchor) currentPage.getByXPath("//*[@id='rso']/li[1]/div/h3/a").get(0);
HtmlPage newPage = firstGoogleResult.click();
//HtmlAnchor linkTest = (HtmlAnchor) newPage.getByXPath("//*[@id='contentdiv_left']/div/div[3]/text()[1]");
//HtmlDivision divContent = (HtmlDivision) newPage.getByXPath("\\div[contains(@class, 'contentdiv_leftbox_data')]");
//System.out.println(divContent.asText());
//System.out.print("*************\n\n\n" + newPage.asText());
System.out.println(newPage.asText());
}
}
そうですか
ツイートボタン
つぶやき
プログラム実行後のコンソール。
では、最初の Google 検索結果の XPath が間違っているのでしょうか、それとも別の場所で間違っているのでしょうか?
どうもありがとうございました。