浏览器使用js中ajax实现网页爬虫效果
抓取网页python中pyspider,scrapy,request-html等优秀的库,js中怎么爬取网页呢?
是的,ajax是不能跨域抓取网页,但是我们可以通过nodejs或者同域代理访问来实现网页抓取
1、nodejs实现
var request = require('request'); request('爬取的网页url', function (error, response, body) { if (!error&&response.statusCode == 200) { console.log(body) // 进行存储或下一步处理 } });
2、同域代理
同域代理就是在浏览器url的同一个域名下,前端浏览器js通过ajax将要爬取的网页url传给后端,后端采用php或java进行网页抓取,将爬取的结果返回给js,js进行下一步的处理
$.get("/scrap.php?targeturl=爬取的网页url", function(result){ console.log(result);//下一步处理 });后端php采用
<?php $url = $_GET["targeturl"]; //前端传过来的网址 if($url!=""){ $ch = curl_init(); $timeout = 1; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $output = curl_exec($ch); curl_close($ch); echo $output; } ?>ok,简单得实现了网页爬取
那么接下来在js中如何解析网页,使用jquery,将获取的网页放在dom中进行分析
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>BFW NEW PAGE</title> <script id="bfwone" data="dep=jquery.17&err=0" type="text/javascript" src="http://repo.bfw.wiki/bfwrepo/js/bfwone.js"></script> <script type="text/javascript"> bready(function() { var el = $('<div></div>'); el.html("<html><head><title>titleTest</title></head><body><a href='test0'>test01'</a><a href='test1' id='content'>test02</a><a href='test2'>test03</a></body></html>"); //从后端抓取网页的结果 alert($('#content', el).html()); }); </script> </head> <body> </body> </html>
网友评论0