.net core + headless chrome实现动态网页爬虫

通常的http请求库只可以抓取到网页的静态内容,若是想抓取经过js动态生成的内容能够使用没有gui的browser库,以前许多人会使用phantomjs做为headless browser,不过如今phantomjs团队已经宣布中止更新工做,须要一款替代库,因而这里就采用了headless chrome来进行动态网页内容抓取。php

爬虫实现以下:html

1.在.net core项目中引用以下nuget包linux

Selenium.WebDriver
Selenium.WebDriver.ChromeDriver

注意:引用Selenium.WebDriver.ChromeDriver后,会在代码目录中copy出chromedriver.exe文件,exe文件只能运行与windows平台下,因此咱们须要去网站(http://chromedriver.storage.googleapis.com/index.html)下载当前最新的chromedriver程序linux版,并将程序添加到项目中,属性设置为复制到输出目录。这样导出的程序才能够在linux和windwos平台下都正常运行。chrome

注意2:爬虫的宿主服务器中须要安装和chromedriver一致版本的chrome版本(两个都安装最新版就能够)windows

2.爬虫代码api

class Program
    {
        static void Main(string[] args)
        {
            ChromeOptions op = new ChromeOptions();
            op.AddArguments("--headless");//开启无gui模式
            op.AddArguments("--no-sandbox");//停用沙箱以在Linux中正常运行
            ChromeDriver cd = new ChromeDriver(Environment.CurrentDirectory, op,TimeSpan.FromSeconds(180));
            cd.Navigate().GoToUrl("http://chart.icaile.com/sd11x5.php");
            string text = cd.FindElementById("fixedtable").Text;
            cd.Quit();
            Console.WriteLine(text);
            Console.Read();
        }
    }
相关文章
相关标签/搜索