小白记录.
网站后台有个需求,需要将站内文章遍历出来去百度查询收录结果,找遍各种帖子全部都是从 site 语法查 https://www.baidu.com/s?w=site:www.baidu.com .
当你放到服务器后获取页面代码 解析 你会发现十几次才能正确获取一次查询结果, 造成查询奇慢.
后来仔细查询发现缺少头 下面贴代码 复制可用
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;private static final String BASE_URL = "https://www.baidu.com/s?wd=site:";
/**
* 查询网址是否被收录
*/public Object getIncluded(String url) {
Map<String,Object> map = new HashMap<String, Object>();
boolean a = true;
a = true;
while (a) {
String data = this.html(url);
if(data.length()<2000){
System.out.println(data);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
//找到相关结果数约
String startLabel = "<span class=\"nums_text\">";
String endLabel = "</span>";
int start = data.indexOf(startLabel)+startLabel.length();
int end = data.indexOf(endLabel,start);
String Result = data.substring(start, end);String str = Result;
str=str.trim();
String str2="";
if(str != null && !"".equals(str)){
for(int i=0;i<str.length();i++){
if(str.charAt(i)>=48 && str.charAt(i)<=57){
str2+=str.charAt(i);
}
}
}
map.put("number", str2);
if("0".equals(str2)){map.put("type",false);}else{map.put("type",true);}
a=false;
}
}
return map;
}
/**
* 请求百度搜索结果页,并返回html源码
*/
private String html(String keywords) {
String html = null;
try {
String url = BASE_URL + keywords;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
try {
get.addHeader("Accept-Language","*,*;q=0.9,zh-TW;q=0.9");
get.addHeader("User-Agent", "Chrome/77.0.3865.120 Safari/537.36");
CloseableHttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
if (entity != null) {
html = EntityUtils.toString(entity);
}
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return html;
}