通过Selenium采集数据

Selenium是一个自动化测试工具,可以驱动浏览器器执行特定的动作,如点击,下拉等。同时还可以获取浏览器当前呈现页面的源代码,可见即可爬。

Nuget

1
2
3
4
Selenium.Chrome.WebDriver
Selenium.RC
Selenium.Support
Selenium.WebDriver

爬页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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  等字符,我们需要把他给替换 可以使用Replace

爬WebApi

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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;
}