java爬虫怎么抓取js动态生成的内容

JavaScript06

java爬虫怎么抓取js动态生成的内容,第1张

我用Jsoup写爬虫,一般遇到html返回没有的内容。但是浏览器显示有的内容。都是分析页面的http请求日志。分析页面JS代码来解决。

1、有些页面元素被隐藏起来了->换selector解决

2、有些数据保存在js/json对象中->截取对应的串,分析解决

3、通过api接口调用->伪造请求获得数据

还有一个终极方法

4、使用phantomjs或者casperjs这种headless浏览器

在java类中获取js变量的值,可以使用如下方式:将js变量放到form中的一个;在后台从form中取出变量放到隐藏域中;然后提交表单给要调用变量的页面。这个页面可以就是本身。示例如下:bb.jsp页面:

<pre t="code" l="java"><% String test5 = (String)request.getAttribute("test4")%>

<script type="text/javascript">

var test1 = '111'//定义js变量

document.form.test2.value = test1

//将js变量的值放到form中的一个隐藏域中

var formObj = document.getElementById('passForm')

formObj.submit()

</script>

<form method="post" action="aa.jsp" id ="passForm">

<input id = 'test2' type = 'hidden' name="test2">

</form>

aa.jsp页面中的Java代码:

<%

request.setCharacterEncoding("utf-8")

String txtMsg = request.getParameter("test2")

out.println(txtMsg)

%>