我正在尝试使用无头浏览器进行爬行,以在我正在开发的开源项目中添加 SEO 功能。
项目示例站点通过 Azure 网站部署。
我尝试了几种方法来使用不同的解决方案来完成任务,例如 Selenium .NET(PhantomJSDriver、HTMLUnitDriver、...),甚至是独立的 PhantomJs .exe 文件。
我正在使用无头浏览器,因为该站点基于 DurandalJS,因此它需要执行脚本并等待条件为真才能返回生成的 HTML。出于这个原因,不能使用 WebClient/WebResponse 类或 HTMLAgilityPack 之类的东西,它们在非 JavaScript 网站上工作得很好。
以上所有方法都适用于我的 devbox localhost 环境,但在将站点上传到 Azure 网站时出现问题。使用独立 phantomjs 时,站点在访问 url 端点时冻结,并在一段时间后返回 HTTP 502 错误。如果使用 Selenium Webdriver,我会得到一个
OpenQA.Selenium.WebDriverException: Unexpected error. System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:XXXX
我认为问题在于在 Azure 中运行 .exe 文件而不是代码。我知道可以通过 WebRole/WebWorkers 在 Azure CloudServices 中运行 .exe 文件,但需要留在 Azure 网站中以保持简单。
可以在 Azure 网站中运行无头浏览器吗?有没有人遇到过这种情况?
我的独立 PhantomJS 解决方案的代码是
//ASP MVC ActionResult
public ActionResult GetHTML(string url)
{
string appRoot = Server.MapPath("~/");
var startInfo = new ProcessStartInfo
{
Arguments = String.Format("{0} {1}", Path.Combine(appRoot, "Scripts\\seo\\renderHTML.js"), url),
FileName = Path.Combine(appRoot, "bin\\phantomjs.exe"),
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
StandardOutputEncoding = System.Text.Encoding.UTF8
};
var p = new Process();
p.StartInfo = startInfo;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
ViewData["result"] = output;
return View();
}
// PhantomJS script
var resourceWait = 300,
maxRenderWait = 10000;
var page = require('webpage').create(),
system = require('system'),
count = 0,
forcedRenderTimeout,
renderTimeout;
page.viewportSize = { width: 1280, height: 1024 };
function doRender() {
console.log(page.content);
phantom.exit();
}
page.onResourceRequested = function (req) {
count += 1;
//console.log('> ' + req.id + ' - ' + req.url);
clearTimeout(renderTimeout);
};
page.onResourceReceived = function (res) {
if (!res.stage || res.stage === 'end') {
count -= 1;
//console.log(res.id + ' ' + res.status + ' - ' + res.url);
if (count === 0) {
renderTimeout = setTimeout(doRender, resourceWait);
}
}
};
page.open(system.args[1], function (status) {
if (status !== "success") {
//console.log('Unable to load url');
phantom.exit();
} else {
forcedRenderTimeout = setTimeout(function () {
//console.log(count);
doRender();
}, maxRenderWait);
}
});
对于 Selenium 选项
public ActionResult GetHTML(string url)
{
using (IWebDriver driver = new PhantomJSDriver())
{
driver.Navigate().GoToUrl(url);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.CssSelector("#compositionComplete"));
});
var content = driver.PageSource;
driver.Quit();
return Content(content);
}
}
谢谢!!