PHantom JS在50%的时间内都失败了

时间:2014-08-31 13:12:36

标签: c# .net selenium-webdriver phantomjs bots

我搜索一个文本框,然后尝试用字符串填充它。这是代码:

    var fname = _driver.FindElement(By.Name("iFirstName"), 50);
    if(fname!=null)
    {
        do
        {
            System.Threading.Thread.Sleep(500);
        } while (!fname.Displayed);
        fname.SendKeys(myName);
    }

FindElement函数是这样的:

    public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds)
    {
        if (timeoutInSeconds > 0)
        {
            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
            return wait.Until(drv => drv.FindElement(by));
        }
        return driver.FindElement(by);
    }

有些时候文本框中填充了字符串,有时我会收到此错误:

System.InvalidOperationException: {"errorMessage":"'undefined' is not an object (evaluating '(y(a)?y(a).parentWindow||y(a).defaultView:window).getComputedStyle(a,null).MozTransform.match')","request":{"headers":{"Accept":"application/json, image/png","Connection":"Close","Host":"localhost:59868"},"httpVersion":"1.1","method":"GET","url":"/displayed","urlParsed":{"anchor":"","query":"","file":"displayed","directory":"/","path":"/displayed","relative":"/displayed","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/displayed","queryKey":{},"chunks":["displayed"]},"urlOriginal":"/session/af970250-310e-11e4-8996-210a8c2c5f2a/element/%3Awdc%3A1409489997045/displayed"}}
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse) in c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs:line 1048
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters) in c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs:line 865
   at OpenQA.Selenium.Remote.RemoteWebElement.get_Displayed() in c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebElement.cs:line 187

这里的问题是什么?我甚至在调用所有上述函数之前制作了一个printcreen,并且所有元素都被正确绘制,因此页面被正确加载。

1 个答案:

答案 0 :(得分:6)

问题是我正在设置从列表中随机生成的自定义UserAgent,其中一些UserAgent(Internet Explorer)导致错误:

        PhantomJSOptions options = new PhantomJSOptions();
        int header = GenerateRandomBetween(0,phantomHeader.Count-1);
        options.AddAdditionalCapability("phantomjs.page.settings.userAgent", phantomHeader[header]);

我删除了它们,现在我不再获得例外。