有人可以告诉我如何使用带有 C# 的 Optimus(无头浏览器)nuget 包从 URL 获取响应。我还希望页面上的 javascript 像 phantomjs 一样自动执行。
问问题
1315 次
1 回答
3
相当简单的套件:
先创建一个Engine组件(动态和静态页面通用):
Engine engine = new Engine();
打开要检索的 html 文档的 url:
a) 不等待使用 javascript 添加的任何元素:
engine.OpenUrl("http://google.com").Wait();
b) 等待使用 javascript 添加的任何元素:
engine.OpenUrl("http://google.com")
然后是:
engine.WaitDesappearingOfId("some-id")
engine.WaitId("some-id")
engine.WaitDocumentLoad()
engine.WaitSelector("#some-id")
engine.WaitSelector(".some-class")
现在您打开 url,有两种方法可以执行此操作 - 加载文档(在执行任何 javascript 之前):
更完整的例子:
public static string dynamicLoadingPage()
{
var engine = new Engine();
engine.OpenUrl("https://html5test.com");
var tagWithValue = engine.WaitSelector("#score strong").FirstOrDefault();
System.Console.WriteLine("Score: " + tagWithValue.InnerHTML);
}
否则:
static string staticLoadingPage()
{
var engine = new Engine();
engine.OpenUrl("http://google.com").Wait();
Console.WriteLine("The first document child node is: " + engine.Document.FirstChild);
Console.WriteLine("The first document body child node is: " + engine.Document.Body.FirstChild);
Console.WriteLine("The first element tag name is: " + engine.Document.ChildNodes.OfType<HtmlElement>().First().TagName);
Console.WriteLine("Whole document innerHTML length is: " + engine.Document.DocumentElement.InnerHTML.Length);
}
于 2018-05-03T00:36:11.080 回答