从 C# .NET Core 控制台应用程序中的浏览器页面检查器捕获数据

我的 C# .NET Core 控制台应用程序是一个简单的网络爬虫。在源代码中包含所需数据的页面上,我能够访问所需数据。在可以从窗口复制数据的页面中,在浏览器的页面检查器中查看,但不在源代码中,我被卡住了。

http://img1.mukewang.com/6199aab20001fbea15850601.jpg

请提供我如何获取这些数据的代码示例。


我当前的捕获代码如下:


var htmlCode = string.empty;

using (WebClient client = new WebClient()) // WebClient class inherits IDisposable

{

     // Get the file content without saving it

     htmlCode = client.DownloadString("https://www.wedj.com/dj-photo-video.nsf/firstdance.html");

}

使用上面的代码,您会收到如下所示的源代码:

http://img2.mukewang.com/6199aabf0001b10803640174.jpg

从浏览器检查器中看到的图 1 中显示的数据隐藏在

<div class="entry row">


慕神8447489
浏览 211回答 3
3回答

呼啦一阵风

有几种方法可以实现您的需要(考虑 C# 控制台应用程序)。也许最简单的方法是使用与浏览器实例交互的工具,即 Selenium(用于单元测试)。所以:安装 Selenium.WebDriver nuget 包安装一个浏览器来运行你的应用程序(假设是 chrome)下载浏览器驱动程序 (&nbsp;chromedriver&nbsp;)写一些类似的东西:IWebDriver driver = null;try{&nbsp; &nbsp; ChromeOptions options = new ChromeOptions();&nbsp; &nbsp; options.AddArguments("--incognito");&nbsp; &nbsp; driver = new ChromeDriver(options);&nbsp; &nbsp; driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);&nbsp; &nbsp; driver.Url = "https://www.wedj.com/dj-photo-video.nsf/firstdance.html";&nbsp; &nbsp; var musicTable = driver.FindElement(By.Id("musicTable"));&nbsp; &nbsp; // interact with driver to get data from the page.&nbsp;}&nbsp;finally&nbsp;{&nbsp; &nbsp; if (driver != null)&nbsp; &nbsp; &nbsp; &nbsp;driver.Dispose();&nbsp;}否则,您需要更多地调查网页的工作原理。据我所知,该页面加载了一个 javascript,https://www.wedj.com/dj-photo-video.nsf/musiclist.js,它负责从服务器加载音乐列表。这个js脚本基本上从以下网址加载数据:https : //www.wedj.com/gbmusic.nsf/musicList? open & wedj =1& list = category_firstdance & count =100(你也可以在浏览器中打开它)。排除“(”和“)”,结果是一个你可以解析的json(可能使用newtonsoft.json包):{&nbsp; "more": "yes",&nbsp; "title": "<h1>Most Requested Wedding First Dance Songs<\/h...",&nbsp; "event": "<table class='musicTable g6-table-all g6-small' id='musicTable' borde..."}event 属性包含您需要的数据(您可以使用 HtmlAgilityPack nuget 包来解析它)。专业硒:易于互动行为与您在浏览器中看到的相同缺点硒:您需要安装 chrome 或其他浏览器当您与浏览器交互时浏览器正在运行浏览器下载完整页面(图像、html、js、css...)专业手册:你只加载你需要的不依赖于外部程序(即浏览器)缺点手册:你需要了解 html/js 是如何工作的您需要手动解析 json/html在这种特定情况下,我更喜欢第二种选择。

凤凰求蛊

阅读有关 C# 的 Selenium 自动化工具,但它会打开您想要删除的每个网页,然后例如返回源代码或在该网页上执行某些操作。通常这个工具不是(afaik)用于网络爬虫,但在开始时可能很好,特别是如果您的 dotnet 核心应用程序位于某个虚拟机/docker 上。但请注意,通过浏览器打开不安全的页面可能会有风险。

小唯快跑啊

您可能想尝试 pupeteer 锐利。它允许您获取当前的 HTML 状态。using (var page = await browser.NewPageAsync()){&nbsp; &nbsp; await page.GoToAsync("http://www.spapage.com");&nbsp; &nbsp; var result = await page.GetContentAsync();}https://github.com/kblok/puppeteer-sharp
打开App,查看更多内容
随时随地看视频慕课网APP