C#使用Selenium+PhantomJS抓取数据
作者:挖宝居士 时间:2022-09-13 23:18:02
手头项目需要抓取一个用js渲染出来的网站中的数据。使用常用的httpclient抓回来的页面是没有数据。上网百度了一下,大家推荐的方案是使用PhantomJS。PhantomJS是一个没有界面的webkit浏览器,能够和浏览器效果一致的使用js渲染页面。Selenium是一个web测试框架。使用Selenium来操作PhantomJS绝配。但是网上的例子多是Python的。无奈,下载了python按照教程搞了一下,卡在了Selenium的导入问题上。遂放弃,还是用自己惯用的c#吧,就不信c#上没有。经过半个小时的折腾,搞定(python折腾了一个小时)。记录下这篇博文,让我等搞c#的新手能用上PhantomJS。
第一步:打开visual studio 2017 新建一个控制台项目,打开nuget包管理器。
第二部:搜索Selenium,安装Selenium.WebDriver。注意:如果要使用代理的话最好安装3.0.0版本。
第三步:写下如下图所示的代码。但是执行的时候会报错。原因是找不到PhantomJS.exe。这时候可以去下载一个,也可以继续看第四步。
using OpenQA.Selenium;
using OpenQA.Selenium.PhantomJS;
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var url = "http://www.baidu.com";
IWebDriver driver = new PhantomJSDriver(GetPhantomJSDriverService());
driver.Navigate().GoToUrl(url);
Console.WriteLine(driver.PageSource);
Console.Read();
}
private static PhantomJSDriverService GetPhantomJSDriverService()
{
PhantomJSDriverService pds = PhantomJSDriverService.CreateDefaultService();
//设置代理服务器地址
//pds.Proxy = $"{ip}:{port}";
//设置代理服务器认证信息
//pds.ProxyAuthentication = GetProxyAuthorization();
return pds;
}
}
}
第四步:打开nuget安装Selenium.PhantomJS.WebDriver包。
第五步:运行。可以看到phantomjs.exe被自动下载了。
来源:http://www.cnblogs.com/endlock/p/6423613.html
标签:C#,抓取,数据
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android Studio新建工程默认在build.gradle中加入maven阿里源的问题
2023-04-02 06:33:32
![](https://img.aspxhome.com/file/2023/0/129120_0s.jpg)
VS2015为console.readkey添加代码片段的方法
2023-11-15 05:23:41
![](https://img.aspxhome.com/file/2023/3/108693_0s.png)
Java中常用的设计模式之装饰器模式详解
2021-08-28 07:59:15
![](https://img.aspxhome.com/file/2023/0/88180_0s.png)
C#实现身份证号码验证的方法
2022-11-08 09:15:34
Android中的广播和广播接收器代码实例
2021-09-04 06:44:22
详解Java中的线程池
2023-11-10 16:33:27
![](https://img.aspxhome.com/file/2023/9/59369_0s.png)
Java编程实现基于用户的协同过滤推荐算法代码示例
2022-09-06 12:44:24
WinForm实现最小化到系统托盘方法实例详解
2023-10-05 05:53:30
Unity实现换装系统
2021-08-11 15:27:15
![](https://img.aspxhome.com/file/2023/6/81096_0s.jpg)
java+opencv实现人脸识别功能
2023-02-20 21:52:58
![](https://img.aspxhome.com/file/2023/3/103073_0s.jpg)
C# 根据表格偶数、奇数加载不同颜色
2022-01-19 11:46:05
![](https://img.aspxhome.com/file/2023/1/111071_0s.png)
SpringBoot集成Mybatis+xml格式的sql配置文件操作
2022-12-05 13:14:12
![](https://img.aspxhome.com/file/2023/6/88566_0s.png)
Spring Security使用Lambda DSL配置流程详解
2021-12-23 19:20:32
自己写的java日志类和方法代码分享
2021-08-18 19:34:13
Android 反射注解与动态代理综合使用详解
2023-01-13 12:30:56
![](https://img.aspxhome.com/file/2023/1/139421_0s.jpg)
C#字符串如何提取数值(带小数点)
2023-01-27 06:10:25
![](https://img.aspxhome.com/file/2023/9/94649_0s.jpg)
关于StringUtils.isBlank()的使用及说明
2022-06-04 00:52:24
![](https://img.aspxhome.com/file/2023/9/113189_0s.png)
C#中4种深拷贝方法介绍
2023-01-02 21:16:11
Java多线程之synchronized关键字的使用
2023-12-12 21:46:16
mybatis-plus返回查询总记录数方式
2021-11-27 01:31:34