运行 Azure Web 应用程序上的 Selenium

Running Selenium on Azure Web App

我有一个 Azure Web 应用程序,当我在控制器上调用操作时,我想用它来屏幕抓取网站,就像这样。

var driver = new PhantomJSDriver();
driver.Url = "http://url.com";
driver.Navigate();
var source = driver.PageSource;
var pathElement = driver.FindElementByXPath("//table[@class='someclassname']");

string innerHtml = "";
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
if (js != null)
{
    innerHtml = (string)js.ExecuteScript("return arguments[0].innerHTML;", pathElement);
}
return innerHtml;

这在本地运行良好,但是当我上传到我的 Azure Web 应用程序时,出现此错误

Cannot start the driver service on http://localhost:51169/

我认为这与防火墙有关,因为我需要在第一次应用程序 运行s 时在我的防火墙设置中批准 PhantomJS。我的问题是如何让它在 Azure 中部署工作?甚至有可能吗,或者我是否需要将其配置为一些单元测试并从 Visual Studio 中 运行?

PhantomJS 目前无法在 Azure Web Apps 运行 下的沙箱中运行。请参阅 wiki 了解当前无法正常工作的列表,以及有关沙盒的许多其他信息。

我将在此处 post 这段适用于 Azure 的代码片段。然而,它远不能用于生产,因为我不断收到随机连接错误,例如:

Unable to connect to the remote server inner message: Unable to connect to the remote server inner message: An attempt was made to access a socket in a way forbidden by its access permissions

完全相同的代码在控制台或 windows 应用程序环境中运行良好。

PhantomJSDriver driver = null;
        PhantomJSDriverService service;

        ServicePointManager.ServerCertificateValidationCallback = new
            RemoteCertificateValidationCallback
            (
               delegate { return true; }
            );

        int retry = 0;

        while (driver == null && retry < 3)
        {
            try
            {
                service = PhantomJSDriverService.CreateDefaultService();
                var uri = service.ServiceUrl;
                var port = service.Port;
                service.LocalToRemoteUrlAccess = true;
                var ghostDriverPath = service.GhostDriverPath;
                service.HideCommandPromptWindow = true;
                service.Start();

                var options = new PhantomJSOptions();
                driver = new PhantomJSDriver(service, options);
            }
            catch (Exception ex)
            {
                if (driver != null)
                {
                    driver.Close();
                    driver.Quit();
                    driver = null;
                }
                Thread.Sleep(retry * 1500);

                ServiceAudit.Default.TraceDebug($"Starting web driver failed on {retry} try");
            }
            retry++;
        }

        if (driver == null)
        {
            ServiceAudit.Default.TraceError($"Web driver could not be started");
        }

        return driver;

我会重新考虑您在这里使用 Selenium 的解决方案。 Selenium 用于自动执行 Web 应用程序的手动测试。基本上,自动填写表格、点击按钮等

即使 Selenium 和您的 PhantomJS 驱动程序在您的 Azure 网络应用程序上 运行 没有问题,您也会遇到每个 1 个 Http 请求一个浏览器的瓶颈。我怀疑您很快就会 运行 遇到性能问题。

此外,驱动程序加载 PhantomJS、请求页面、交互和关闭 PhantomJS 所需的时间很慢。

在您的情况下,您似乎没有与源站点进行交互,您只需要数据。所以也许只解析 HTML DOM 就足够了。

听起来您应该做的是发布到 Azure WebRole。 查看此答案...