webmagic+selenium模拟浏览器下载动态网页

4 篇文章 0 订阅

现在绝大多数网页都是动态生成的,那么学习爬虫就意味着更加困难。若是静态网页,只需要了解如何连接网络和分析网页源代码提取标签信息即可,但是动态网页的话,就需要使用到一些特定的框架来爬取了。比较实用的爬取动态网页信息的其中一个工具就是selenium了。先来看看要怎样使用webmagic和selenium来模拟浏览器启动吧。

import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.downloader.selenium.SeleniumDownloader;
import us.codecraft.webmagic.processor.example.GithubRepoPageProcessor;
 
public class LiuLanQiTest {
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//selenium系统配置,其中的路径写自己config文件的路径
		System.setProperty("selenuim_config", "D:\\jse-workspace\\WebMagicTest\\Study\\src\\main\\java\\Four\\config.ini");	
		Spider.create(new GithubRepoPageProcessor())//调用一个webmagic中封装好的一个网页爬取类
		.addUrl("http://www.baidu.com")//要爬取的网页
		//浏览器驱动(动态网页信息通过模拟浏览器启动获取)
		.setDownloader(new SeleniumDownloader("D:\\ChromeDriver\\chromedriver_win32(2)\\chromedriver.exe"))
		.thread(3)//启动n个线程(此语句表示启动3个线程)
		.run();//启动爬虫,会阻塞当前线程执行(及n个线程不是同时执行的)
//		。runAsync();//启动爬虫,当前线程继续执行(及n个线程同时执行)
		}
}

当出现如下页面时,说明启动浏览器成功。
在这里插入图片描述
!!!需要注意的是,用此代码模拟浏览器启动的时候,要先将webmagic和selenium所需要的包全部导入到所建项目中,并且下载过chrome驱动。

若创建的项目是maven项目,则可以直接在pom.xml文件中加入如下语句:

    <dependency>
	    <groupId>us.codecraft</groupId>
	    <artifactId>webmagic-core</artifactId>
	    <version>0.7.3</version>
	</dependency>
	<dependency>
	    <groupId>us.codecraft</groupId>
	    <artifactId>webmagic-extension</artifactId>
	    <version>0.7.3</version>
	</dependency>
	<dependency>
		<groupId>us.codecraft</groupId>
		<artifactId>webmagic-selenium</artifactId>
		<version>0.7.3</version>
	</dependency>
	<dependency>
		<groupId>org.seleniumhq.selenium</groupId>
		<artifactId>selenium-java</artifactId>
		<version>3.0.1</version>
	</dependency>
	<dependency>
		<groupId>org.seleniumhq.selenium</groupId>
		<artifactId>selenium-chrome-driver</artifactId>
		<version>3.0.1</version>
	</dependency>

再有就是要在所建项目下新建config配置文件,文件内容可以参照我的config.ini文件来写,文件内容如下:

# What WebDriver to use for the tests
#driver=phantomjs
#driver=firefox
driver=chrome
#driver=http://localhost:8910
#driver=http://localhost:4444/wd/hub

# PhantomJS specific config (change according to your installation)
#phantomjs_exec_path=/Users/Bingo/bin/phantomjs-qt5
#phantomjs_exec_path=d:/phantomjs.exe
chrome_exec_path=C:\Users\sky\AppData\Local\Google\Chrome\Application\chrome.exe
#phantomjs_driver_path=/Users/Bingo/Documents/workspace/webmagic/webmagic-selenium/src/main.js
#phantomjs_driver_loglevel=DEBUG
chrome_driver_loglevel=DEBUG

转载自:https://blog.csdn.net/without_scruple/article/details/78367412

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值