4

SeleniumにTLDをクロールさせ、見つかった404のリストを段階的にエクスポートすることは可能ですか?

私は数時間Windowsマシンで立ち往生していて、*nix...の快適さに戻る前にいくつかのテストを実行したいと思っています。

4

1 に答える 1

1

私はPythonも、その一般的に使用されるライブラリもよく知りませんが、おそらく次のようなことをします(例としてC#コードを使用しますが、概念を適用する必要があります)。

// WARNING! Untested code here. May not completely work, and
// is not guaranteed to even compile.

// Assume "driver" is a validly instantiated WebDriver instance
// (browser used is irrelevant). This API is driver.get in Python,
// I think.
driver.Url = "http://my.top.level.domain/";

// Get all the links on the page and loop through them,
// grabbing the href attribute of each link along the way.
// (Python would be driver.find_elements_by_tag_name)
List<string> linkUrls = new List<string>();
ReadOnlyCollection<IWebElement> links = driver.FindElement(By.TagName("a"));
foreach(IWebElement link in links)
{
    // Nice side effect of getting the href attribute using GetAttribute()
    // is that it returns the full URL, not relative ones.
    linkUrls.Add(link.GetAttribute("href"));
}

// Now that we have all of the link hrefs, we can test to
// see if they're valid.
List<string> validUrls = new List<string>();
List<string> invalidUrls = new List<string>();
foreach(string linkUrl in linkUrls)
{
    HttpWebRequest request = WebRequest.Create(linkUrl) as HttpWebRequest;
    request.Method = "GET";

    // For actual .NET code, you'd probably want to wrap this in a
    // try-catch, and use a null check, in case GetResponse() throws,
    // or returns a type other than HttpWebResponse. For Python, you
    // would use whatever HTTP request library is common.

    // Note also that this is an extremely naive algorithm for determining
    // validity. You could just as easily check for the NotFound (404)
    // status code.
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    if (response.StatusCode == HttpStatusCode.OK)
    {
        validUrls.Add(linkUrl);
    }
    else
    {
        invalidUrls.Add(linkUrl);
    }
}

foreach(string invalidUrl in invalidUrls)
{
    // Here is where you'd log out your invalid URLs
}

この時点で、有効なURLと無効なURLのリストがあります。これをすべて、TLD URLを渡すことができるメソッドにまとめて、有効な各URLで再帰的に呼び出すことができます。ここで重要なのは、リンクの有効性を実際に判断するためにSeleniumを使用していないということです。また、本当に再帰的なクロールを実行している場合は、リンクを「クリック」して次のページに移動する必要はありません。むしろ、ページにあるリンクに直接移動することをお勧めします。

プロキシを介してすべてを実行し、その方法で応答コードをキャプチャするなど、他のアプローチをとることができます。それはあなたがあなたのソリューションをどのように構築することを期待するかに少し依存します。

于 2013-06-18T22:01:34.487 に答える