C#爬虫(Selenium和WeiAPI)

目前对网页的爬虫一个是对网页直接爬取数据和WeiAPI的方式爬取,这取决于网址用的何时渲染的数据,而后展现在网页中。html

首先咱们对某一个网址准备爬取数据时候,你须要去研究这个网址是后台给前台是数据仍是网页,这个时候我推荐 Fiddler 或者Fiddler.exe 和  postman  这两个软件进行研究,具体安装方式和使用方式可百度,有不少的教程;若是你不想下载,那在浏览器中按住 F12,而后以下图web

 

 

  若是Response里面是一个HTML,那说明这个不是WebAPI的方式,这个时候你就得选择网页爬虫,在C#NuGet里面添加 如下几个网页爬虫

ChromeOptions options = new ChromeOptions();        
  // 不显示浏览器
 options.AddArgument("--headless");
 // GPU加速可能会致使Chrome出现黑屏及CPU占用率太高,因此禁用
 options.AddArgument("--disable-gpu");
 //禁用浏览器的保存密码选项
 options.AddUserProfilePreference("credentials_enable_service", false);
 options.BinaryLocation = webClientUrl;
  IWebDriver driver = new ChromeDriver(options);
//进入的网址
 driver.Navigate().GoToUrl(LoingUrl);//LoingUrl 就得须要链接的地址
// 设置页面加载时间
driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(2000);
driver.FindElement(By.Id("txtUsername")).SendKeys(userName);                
driver.FindElement(By.Id("txtPassword")).SendKeys(userPassword);
driver.FindElement(By.Id("imgBtnSignIn")).Click();
driver.Navigate().GoToUrl(listUrl);//须要获取数据的地址
var _trselector = driver.FindElements(By.CssSelector("这里是你须要获取数据的Clss或者ID对应的名称"));// 定位到表格下的每个tr的数据  
好比<div id="test_id"><div class="test">--------------</div></div> 那就是 by.CssSelector("#test_id .test")
HtmlDocument htmlDocument = new HtmlDocument();//初始化一个HTMLDocument对象 htmlDocument.LoadHtml(_trselector .GetAttribute("innerHTML"));//这里是获取元素里面的内容 而后数据里面可能会有\n\t &nbsp;等字符,咱们须要把他给替换 可使用Replace

 

 

 二、webAPI 浏览器

  若是Response是这种,这后台采用的是WebAPI的方式,这个时候咱们去Headers里面看看,RequestURL就是WebAPI的方法,而FormData就是参数,把URL和参数拼接一块儿便可获得数据,而后获取数据便可,代码以下。app

 

 

 

 

 

 

 

 

 

 

 

 

 

 WebAPI代码less

public void  GetData(){
      CookieContainer httpCookie = DoLogin(UserName, Password);
     if (httpCookie == null)    return;//登陆是否成功
     //获取WebApi的数据
      string result_CIS = GetCISList(CISURL, httpCookie);
        ……………………这里就是对获取的数据进行处理解析
}   
private CookieContainer DoLogin(string username, string password, string LoginURL)
{
var client = new RestClient(LoginURL); var request = new RestRequest(Method.POST); //UserName=OECSHA&Password=Oecsha123!&OfficeCode= request.AddParameter("application/x-www-form-urlencoded", $"UserName={username}&Password={password}&OfficeCode=", ParameterType.RequestBody); client.CookieContainer = new System.Net.CookieContainer(); IRestResponse response = client.Execute(request); if (!response.IsSuccessful) return null; return client.CookieContainer; } private string GetCISList(string cISURL, CookieContainer httpCookie) { var client = new RestClient(cISURL+ "参数"); var request = new RestRequest(Method.POST);//采用的方式 client.CookieContainer = httpCookie; IRestResponse response = client.Execute(request); if (!response.IsSuccessful) return null; return response.Content; }
相关文章
相关标签/搜索