我有以下link,当我通过Chrome打开链接然后右键单击该页面然后选择"另存为"将页面保存为HTML文件(c:\ temp \ cu2.html)
保存后,我可以用HTML编辑器(比如VS2015)打开这个cu2.html文件,我可以看到 在文件内部,有标签,如下所示
但是,如果我用IE11(而不是Chrome)打开链接,然后将同一页面保存为HTML文件,我根本找不到这个标签。实际上,从IE11保存的html文件与我在下面的PowerShell脚本中提取的内容相同。
#Requires -version 4.0
$url = 'https://support.microsoft.com/en-us/help/4052574/cumulative-update-2-for-sql-server-2017';
$wr = Invoke-WebRequest $url;
$wr.RawContent.contains('<table') # returns false
$wr.RawContent | out-file -FilePath c:\temp\cu2_ps.html -Force; #same as the file saved from the webpage to html file in IE
所以我的问题是:
为什么Chrome中保存的网页(如html文件)与IE中的网页不同?
如何使用PowerShell(或C#)将此类网页保存为HTML文件(与Chrome中保存的文件相同)?
提前感谢您的帮助。
答案 0 :(得分:3)
页面使用AngularJS和jQuery。这意味着文档就绪后将加载一些内容。因此,当您使用select iif(DATEPART(HOUR, GETDATE()) < 9,
dateadd(hh, 9, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)),
getdate())
发送请求时,您只会收到该页面的原始内容。其他内容将在一段时间后加载。
要解决此问题,您可以自动化IE以获得预期结果。它足以等待页面准备好,还等待运行AngularJs逻辑并下载所需内容,然后获取文档元素的内容:
Invoke-WebRequest
答案 1 :(得分:0)
您可以使用Selenium.WebDriver和Selenium.Chrome.WebDriver个软件包下载并保存html内容:
var service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
var options = new ChromeOptions();
options.AddArgument("headless");
using (var driver = new ChromeDriver(service, options))
{
driver.Url = "https://support.microsoft.com/en-us/help/4052574/cumulative-update-2-for-sql-server-2017";
File.WriteAllText("cu2_ps.html", driver.PageSource);
}
但这意味着你需要安装chrome。您也可以使用IE驱动程序,但最好还是使用其他答案中建议的IE COM自动化。