2011-07-21 10 views
2

HtmlUnitでYouTubeを検索できるのかと思います。私はコードを書くようになった、ここにそれは:HtmlUnitでYouTubeを検索する方法

​​3210

私はどのようにテキストを検索フィールドに入力し、検索ボタンを押すかわからない。

HtmlUnitについてのチュートリアルを見ましたが、名前がgetElementByNameのメソッドを使用しているため問題がありますが、YouTubeの検索ボタンには名前はなく、IDのみです。誰か助けてくれますか?

EDIT:私は上記のコードを編集しましたが、今は最初のページからYouTubeのリンクを取得しています。しかし、その前に、私はアップロード日付でソートして、リンクをつかむ必要があります。誰かがソートを手伝うことができますか?

答えて

3

をあなたが働いていることを得れば

、YouTubeの検索フォームのためのセレクタは次のようになり、「.search-用語」と送信ボタンのセレクタは次のようになります回避策があります。フォームに独自のボタンを追加してフォームを送信することができます。ここで

は、コメント付きのコードサンプルです:

import java.io.IOException; 
import java.net.MalformedURLException; 

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; 
import com.gargoylesoftware.htmlunit.WebClient; 
import com.gargoylesoftware.htmlunit.html.HtmlButton; 
import com.gargoylesoftware.htmlunit.html.HtmlForm; 
import com.gargoylesoftware.htmlunit.html.HtmlPage; 
import com.gargoylesoftware.htmlunit.html.HtmlTextInput; 

public class HtmlUnitExampleTestBase { 
    public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException { 
     WebClient webClient = new WebClient(); 
     webClient.setThrowExceptionOnScriptError(false); 

     // This is equivalent to typing youtube.com to the adress bar of browser 
     HtmlPage currentPage = webClient.getPage("http://www.youtube.com"); 

     // Get form where submit button is located 
     HtmlForm searchForm = (HtmlForm) currentPage.getElementById("masthead-search"); 

     // Get the input field. 
     HtmlTextInput searchInput = (HtmlTextInput) currentPage.getElementById("masthead-search-term"); 
     // Insert the search term. 
     searchInput.setText("Nyan Cat"); 

     // Workaround: create a 'fake' button and add it to the form. 
     HtmlButton submitButton = (HtmlButton) currentPage.createElement("button"); 
     submitButton.setAttribute("type", "submit"); 
     searchForm.appendChild(submitButton); 

     // Workaround: use the reference to the button to submit the form. 
     HtmlPage newPage = submitButton.click(); 

     System.out.println(newPage.asText()); 
    } 
} 
+0

それは動作します。今は、デフォルト以外の基準で結果を並べ替えるだけです。デフォルトは関連性によってソートされます。アップロード日付順にソートする方法は? –

+0

@ИванБишевац:新しい質問をする方がいいでしょうか? – Jasper

+0

さて、私はそれをやるでしょう。 –

1

HtmlUnitは問題ありませんが、ウェブの自動化にはWatirまたはSeleniumを使用することをお勧めします。

HtmlUnitの弱点の1つは、jQueryのような方法でDOM要素を取得するためのセレクタメソッドが欠けていることです。 css-selectorプロジェクトをチェックしてください。これはHtmlUnitに追加され、非常に簡単に必要なことを行うのに役立ちます。イントロはGooder Codeです。私はHtmlUnit専門家だが、「.search-ボタン」

+0

あなたはワチールまたはSelemiumを取るために私をお勧めですか?私はここで、多くの人々がSelenuimを推薦するフォーラムで聞いた。 –

+0

@ИванБишевац:[Watir対Selenium v​​s Sahiの比較](http://stackoverflow.com/questions/606550/watir-vs-selenium-vs-sahi/643124#643124)です。 – Jasper

+0

@ИванБишевац:私はそれらの両方が好きです。私が本当にすばやく簡単に録画/再生したいと思っていて、見たい単純な機能テストが必要な場合は、私はSeleniumを使用します。より強力な制御構造、ロジック、および/または自動化が必要な場合は、Watirを使用します。 – jkraybill