我是Selenium和c#的新手,所以我已經走到了死衚衕。我需要知道如何檢查天氣圖像src文件是否存在。當我的意思是存在時,它是否顯示在頁面上(而不是在沒有圖像時出現的紅色x框)。Selenium c# - 我如何測試一個圖像src文件存在(驗證圖像是否顯示在頁面上)
我試過file.exists(@c://imagename)
;和System.File.Exists
。
我不知道這是否正確。
任何幫助將是偉大的!我的頭與此
感謝
我是Selenium和c#的新手,所以我已經走到了死衚衕。我需要知道如何檢查天氣圖像src文件是否存在。當我的意思是存在時,它是否顯示在頁面上(而不是在沒有圖像時出現的紅色x框)。Selenium c# - 我如何測試一個圖像src文件存在(驗證圖像是否顯示在頁面上)
我試過file.exists(@c://imagename)
;和System.File.Exists
。
我不知道這是否正確。
任何幫助將是偉大的!我的頭與此
感謝
你不能這樣做炸,至少不能僅僅用硒。根據您測試的瀏覽器,您可能會查看磁盤上的瀏覽器緩存並找到該文件,但並非所有瀏覽器都將所有內容都緩存到磁盤,並且找出文件名可能非常困難。
沒有硒,當然,你可以使用curl,wget等等。下載圖像文件,或者您可以屏幕截圖瀏覽器並自己搜索「紅色X盒子」。但是這兩個都不是不錯的答案。
謝謝你看看那個;) – Lou 2011-06-02 15:21:45
假設的圖像的路徑是相對src屬性中,你將需要解決URL,然後運行一個類似於在這個答案提出了一個試驗:
Test to see if an image exists in C#
如果你真的需要檢查,如果圖像存在,並已經部署了(我懷疑,如果這是一個qorthwhile測試要誠實),你可以使用類似下面的代碼:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://full-path-to-your-image.png");
request.Method = "HEAD";
bool exists;
try
{
request.GetResponse();
exists = true;
}
catch
{
exists = false;
}
它基本上是檢查URL(圖像的在你的情況) ,看看圖像是否存在。
如果你需要一隻手與它轉了一圈又要求;)
謝謝。我通過selenium.GetAttribute(「// descendant :: * [@ class ='name'] [1]/a/img/@ src」)找到了圖像路徑。這將返回結果/StyleLib/test.jpg這是圖像路徑。所以我知道圖像存在,我只是不知道如何測試它是否存在於頁面上。希望這是有道理的 – Lou 2011-06-02 15:21:05
樓 - 要清楚,你的測試並不知道圖像存在。無論瀏覽器是否能夠加載圖像,都會設置SRC屬性。例如,''是合法的,並且提取它的SRC屬性將產生'http:// no.such.domain/no.such.jpg',即使瀏覽器明顯沒有下載不存在的圖像。 – 2011-06-02 15:33:08
好吧,我明白了...所以要驗證圖像是否存在,我只是使用標準iselementpresent?但不是在scr上? – Lou 2011-06-02 15:42:39
我的解決方案是檢查該文件的長度。 你可以修改這個解決方案,您的需要:
/// <summary>
/// Gets the file lenght from location.
/// </summary>
/// <param name="location">The location where file location sould be located.</param>
/// <returns>Lenght of the content</returns>
public int GetFileLenghtFromUrlLocation(string location)
{
int len = 0;
int timeoutInSeconds = 5;
// paranoid check for null value
if (string.IsNullOrEmpty(location)) return 0;
// Create a web request to the URL
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(location);
myRequest.Timeout = timeoutInSeconds * 1000;
myRequest.AddRange(1024);
try
{
// Get the web response
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
// Make sure the response is valid
if (HttpStatusCode.OK == myResponse.StatusCode)
{
// Open the response stream
using (Stream myResponseStream = myResponse.GetResponseStream())
{
if (myResponseStream == null) return 0;
using (StreamReader rdr = new StreamReader(myResponseStream))
{
len = rdr.ReadToEnd().Length;
}
}
}
}
catch (Exception err)
{
throw new Exception("Error saving file from URL:" + err.Message, err);
}
return len;
}
如果該文件的計算機或局域網上存在,我不知道爲什麼'System.File.Exists'是行不通的。你是如何嘗試並使用它的? – 2011-06-02 15:00:19
我有一個字符串,它具有src屬性,然後調用它來查看文件是否存在。 – Lou 2011-06-02 15:52:14