package web.play.rss.util;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Hashtable;
import web.play.rss.util.dao.SpiderDAO;
public class GetWeb {
private int webDepth = 2;// 爬虫深度
private int intThreadNum = 10;// 线程数
private String strHomePage = "";// 主页地址
private String myDomain;// 域名
private String fPath = "web";// 储存网页文件的目录名
private ArrayList<String> arrUrls = new ArrayList<String>();// 存储未处理URL
private ArrayList<String> arrUrl = new ArrayList<String>();// 存储所有URL供建立索引
private Hashtable<String, Integer> allUrls = new Hashtable<String, Integer>();// 存储所有URL的网页号
private Hashtable<String, Integer> deepUrls = new Hashtable<String, Integer>();// 存储所有URL深度
private int intWebIndex = 0;// 网页对应文件下标,从0开始
private String charset = "GBK";
private String report = "";
private long startTime;
private int webSuccessed = 0;
private int webFailed = 0;
private String searchKey = "";
private List searchedUrl = new ArrayList();//成功的url
private List searchedKey = new ArrayList();//搜索到的关键字列表
private boolean searchCurrent = false;
private boolean saveUrl = true;
private boolean saveSearchKey = true;
private boolean debug = false;
private void setDebug(boolean _d){
this.debug = _d ;
}
public void setSaveSearchKey(boolean saveSearchKey) {
this.saveSearchKey = saveSearchKey;
}
public void setSaveUrl(boolean saveUrl) {
this.saveUrl = saveUrl;
}
public void setSearchCurrent(boolean searchCurrent) {
this.searchCurrent = searchCurrent;
}
public String getSearchKey(){
return searchKey;
}
public List getSearchedKey() {
return searchedKey;
}
public List getSearchedUrl() {
return searchedUrl;
}
public GetWeb(String s,String key) {
this.strHomePage = s;
this.searchKey = key;
}
public String getHomePage() {
return this.strHomePage;
}
public GetWeb(String s, int i) {
this.strHomePage = s;
this.webDepth = i;
}
public synchronized void addWebSuccessed() {
webSuccessed++;
}
public synchronized void addWebFailed() {
webFailed++;
}
public synchronized void addReport(String s) {
try {
report += s;
PrintWriter pwReport = new PrintWriter(new FileOutputStream(
"report.txt"));
pwReport.println(report);
pwReport.close();
} catch (Exception e) {
System.out.println("��ɱ����ļ�ʧ��!");
}
}
public synchronized String getAUrl() {
String tmpAUrl = arrUrls.get(0);
arrUrls.remove(0);
return tmpAUrl;
}
public synchronized String getUrl() {
String tmpUrl = arrUrl.get(0);
arrUrl.remove(0);
return tmpUrl;
}
public synchronized Integer getIntWebIndex() {
intWebIndex++;
return intWebIndex;
}
public void getWebByHomePage() {
System.out.println("start ... ...");
if( searchCurrent ){
searchKey(getContent( this.getHomePage() ) ,this.getSearchKey());
}
startTime = System.currentTimeMillis();
this.myDomain = getDomain();
if (myDomain == null) {
System.out.println("Wrong input!");
// System.exit(1);
return;
}
// System.out.println("Homepage = " + strHomePage);addReport("Homepage = " + strHomePage + "!\n");System.out.println("Domain = " + myDomain);addReport("Domain = " + myDomain + "!\n");
arrUrls.add(strHomePage);
arrUrl.add(strHomePage);
allUrls.put(strHomePage, 0);
deepUrls.put(strHomePage, 1);
// File fDir = new File(fPath);
// if (!fDir.exists()) {
// fDir.mkdir();
// }
// System.out.println("Start!");this.addReport("Start!\n");
String tmp = getAUrl();
this.getWebByUrl(tmp, charset, allUrls.get(tmp) + "");
int i = 0;
for (i = 0; i < intThreadNum; i++) {
new Thread(new Processer(this)).start();
}
while (true) {
if (arrUrls.isEmpty() && Thread.activeCount() == 1) {
long finishTime = System.currentTimeMillis();
long costTime = finishTime - startTime;
System.out.println("\n\n\n\n\nFinished!");
System.out.println("Start time = " + startTime + " "
+ "Finish time = " + finishTime + " "
+ "Cost time = " + costTime + "ms");
// addReport("Start time = " + startTime + " "
// + "Finish time = " + finishTime + " "
// + "Cost time = " + costTime + "ms" + "\n");
System.out.println("Total url number = "
+ (webSuccessed + webFailed) + " Successed: "
+ webSuccessed + " Failed: " + webFailed);
// addReport("Total url number = " + (webSuccessed + webFailed)
// + " Successed: " + webSuccessed + " Failed: "
// + webFailed + "\n");
String strIndex = "";
String tmpUrl = "";
while (!arrUrl.isEmpty()) {
tmpUrl = getUrl();
strIndex += "Web depth:" + deepUrls.get(tmpUrl)
+ " Filepath: " + fPath + "/web"
+ allUrls.get(tmpUrl) + ".htm" + " url:" + tmpUrl
+ "\n\n";
}
// System.out.println(strIndex);
try {
PrintWriter pwIndex = new PrintWriter(new FileOutputStream(
"fileindex.txt"));
pwIndex.println(strIndex);
pwIndex.close();
} catch (Exception e) {
System.out.println("��������ļ�ʧ��!");
}
break;
}
}
}
private String getContent(String strUrl) {
try {
URL pageUrl = new URL(strUrl);
// Open connection to URL for reading.
BufferedReader reader = new BufferedReader(new InputStreamReader(
pageUrl.openStream()));
// Read page into buffer.
String line;
StringBuffer pageBuffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
pageBuffer.append(line);
if(debug){
System.out.println(line);
}
}
return pageBuffer.toString();
} catch (Exception e) {
}
return null;
}
public void getWebByUrl(String strUrl, String charset, String fileIndex) {
try {
// if(charset==null||"".equals(charset))charset="utf-8";
// System.out.println("Getting web by url: " + strUrl);
// addReport("Getting web by url: " + strUrl + "\n");
URL url = new URL(strUrl);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
InputStream is = null;
is = url.openStream();
// String filePath = fPath + "/web" + fileIndex + ".htm";
// PrintWriter pw = null;
// FileOutputStream fos = new FileOutputStream(filePath);
// OutputStreamWriter writer = new OutputStreamWriter(fos);
// pw = new PrintWriter(writer);
BufferedReader bReader = new BufferedReader(new InputStreamReader(
is));
StringBuffer sb = new StringBuffer();
String rLine = null;
String tmp_rLine = null;
while ((rLine = bReader.readLine()) != null) {
tmp_rLine = rLine;
int str_len = tmp_rLine.length();
if (str_len > 0) {
sb.append("\n" + tmp_rLine);
// pw.println(tmp_rLine);
// pw.flush();
if (deepUrls.get(strUrl) < webDepth)
getUrlByString(tmp_rLine, strUrl);
}
tmp_rLine = null;
}
is.close();
// pw.close();
if(! searchCurrent ){
searchKey(getContent( strUrl ) ,this.getSearchKey());
}
if(saveUrl){
searchedUrl.add(strUrl);
}
// System.out.println("Get web successfully! " + strUrl);
// addReport("Get web successfully! " + strUrl + "\n");
addWebSuccessed();
} catch (Exception e) {
System.out.println("Get web failed! " + strUrl);
// addReport("Get web failed! " + strUrl + "\n");
addWebFailed();
}
}
public String getDomain() {
String reg = "(?<=http\\://[a-zA-Z0-9]{0,100}[.]{0,1})[^.\\s]*?\\.(com|cn|net|org|biz|info|cc|tv)";
Pattern p = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(strHomePage);
boolean blnp = m.find();
if (blnp == true) {
return m.group(0);
}
return null;
}
public List searchKey(String content , String key){
List list = new ArrayList();
try{
Pattern p = Pattern.compile(key, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(content);
boolean blnp = m.find();
while (blnp == true) {
String searched = m.group(0);
if(saveSearchKey && searched != null && !searched .trim().replace(" ","") .equals("null") && !searched.trim().replace(" ","") .equals("")){
searchedKey.add(searched);
}
blnp = m.find();
}
}catch (Exception e) {
}
return list;
}
public void getUrlByString(String inputArgs, String strUrl) {
String tmpStr = inputArgs;
String regUrl = "(?<=(href=)[\"]?[\']?)[http://][^\\s\"\'\\?]*("+ myDomain + ")[^\\s\"\'>]*";
Pattern p = Pattern.compile(regUrl, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(tmpStr);
boolean blnp = m.find();
// int i = 0;
while (blnp == true) {
if (!allUrls.containsKey(m.group(0))) {
// System.out.println("Find a new url,depth:" + (deepUrls.get(strUrl) + 1) + " " + m.group(0));
// addReport("Find a new url,depth:" + (deepUrls.get(strUrl) + 1) + " " + m.group(0) + "\n");
arrUrls.add(m.group(0));
arrUrl.add(m.group(0));
allUrls.put(m.group(0), getIntWebIndex());
deepUrls.put(m.group(0), (deepUrls.get(strUrl) + 1));
}
tmpStr = tmpStr.substring(m.end(), tmpStr.length());
m = p.matcher(tmpStr);
blnp = m.find();
}
}
public static void main(String[] args) {
String url = "http://hi.baidu.com/guoyan227/blog/item/b759012375f0a846925807df.html";//http://www.google.com.hk/search?q=tom&hl=zh-CN&safe=strict&start=10&sa=N
// url = "http://www.google.com.hk/search?hl=zh-CN&q=javagoogle";
// url = "http://www.baidu.com/s?bs=%C0%B5%CE%B0%C3%B7&f=8&wd=%CB%F9%D3%D0%BA%BA%D7%D6";
String key = "[0|2|5|6][0][0][0-9]{3}";
// url = "http://hi.baidu.com/festsoft/blog/item/171feb8860eee492a5c27256.html";
// key = "[\u4e00-\u9fa5]{0,1}";//[\u4e00-\u9fa5]{0,}字词句
GetWeb gw = new GetWeb(url,key);
// gw.setSaveSearchKey(false);
gw.setSearchCurrent(true);
gw.getWebByHomePage();
List list = gw.getSearchedKey();
SpiderDAO dao = new SpiderDAO();
// dao.getStock();
for(int i=0;i<list.size();i++){
// dao.addStockNum((String)list.get(i), "", "");
System.out.println(list.get(i));
}
System.out.println("gsize:"+list.size());
if(list.size() == 0){
list = gw.getSearchedUrl();
System.out.println(list.size());
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
}
}
class Processer implements Runnable {
GetWeb gw;
public Processer(GetWeb g) {
this.gw = g;
}
public void run() {
// Thread.sleep(5000);
while (!arrUrls.isEmpty()) {
String tmp = getAUrl();
getWebByUrl(tmp, charset, allUrls.get(tmp) + "");
}
}
}
}
package web.play.rss.util.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.provideo.ibox.connection.DBConnSourceByStruts;
public class SpiderDAO {
Connection con = null;
PreparedStatement ps = null;
public boolean addStockNum(String num,String name,String type){
boolean isadd = false ;
String sql = "insert ignore into Stock (StockNum, StockName, StockType, StockAddr, StockActive)values( ?, ?, ?, '', 2)";
try {
con = new DBConnSourceByStruts().getConnection();
// if(con == null){
// Connectioner conner = new Connectioner();
//
// con = conner.getConnection();
// }
} catch (Exception e1) {
e1.printStackTrace();
}
try{
ps = con.prepareStatement(sql);
ps.setString(1, num);
ps.setString(2, name);
ps.setString(3, type);
ps.execute();
isadd = true;
}catch (Exception e) {
e.printStackTrace();
}finally{
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return isadd;
}
public String getStock(){
String rtnStr = "";
String sql = "select * from Stock";
Connection con = null;
try {
con = new DBConnSourceByStruts().getConnection();
} catch (SQLException e1) {
e1.printStackTrace();
}
try{
ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString(1) +" "+rs.getString(2) +" " + rs.getString(3));
}
}catch (Exception e) {
e.printStackTrace();
}finally{
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return rtnStr;
}
}
package web.play.rss.util.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class Connectioner {
public Connection getConnection() {
Connection con = null;
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url = "jdbc:mysql://localhost/dbname?user=root&password=123456";
// myDB为数据库名
con = DriverManager.getConnection(url);
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void main(String[] args) {
Connectioner con = new Connectioner();
con.getConnection();
}
}
Stock CREATE TABLE `Stock` (
`Oid` int(64) NOT NULL auto_increment,
`StockNum` varchar(200) unique default NULL,
`StockName` varchar(200) default NULL,
`StockType` varchar(200) default NULL,
`StockAddr` varchar(200) default NULL,
`StockActive` varchar(20) default NULL,
PRIMARY KEY (`Oid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
分享到:
相关推荐
matplotlib-3.6.3-cp39-cp39-linux_armv7l.whl
numpy-2.0.1-cp39-cp39-linux_armv7l.whl
基于springboot个人公务员考试管理系统源码数据库文档.zip
onnxruntime-1.13.1-cp310-cp310-win_amd64.whl
基于springboot的西山区家政服务网站源码数据库文档.zip
Linux环境下,关于C++静态库的封装和调用代码。 TestLib是库目录。 TestLibCall是调用库的目录。
基于springboot软件技术交流平台源码数据库文档.zip
numpy-1.20.1-cp39-cp39-linux_armv7l.whl
ASP.NET酒店管理系统源码(WPF) 一、源码特点 采用WPF进行开发的酒店管理系统源码,界面相当美观,功能齐全 二、菜单功能 1、预订登记:可选择入住时间、离店时间、所在城市、证件类型,保存、删除、查询、返回 2、住宿结算:新增入住、保存、删除、查询、返回 3、今日盘点:查询、返回 4、查询统计: 5、房间管理:增加房间类型、删除类型、增加房间、删除房间、保存、返回 6、用户管理:增加用户、删除用户、保存、返回 7、系统配置:基本功能 8、显示当前系统时间等功能的实现
坠落的天空小游戏图片和代码
论文描述:该论文研究了某一特定领域的问题,并提出了新的解决方案。论文首先对问题进行了详细的分析和理解,并对已有的研究成果进行了综述。然后,论文提出了一种全新的解决方案,包括算法、模型或方法。在整个研究过程中,论文使用了合适的实验设计和数据集,并进行了充分的实验验证。最后,论文对解决方案的性能进行了全面的评估和分析,并提出了进一步的研究方向。 源码内容描述:该源码实现了论文中提出的新的解决方案。源码中包含了算法、模型或方法的具体实现代码,以及相关的数据预处理、实验设计和性能评估代码。源码中还包括了合适的注释和文档,以方便其他研究者理解和使用。源码的实现应该具有可读性、可维护性和高效性,并能够复现论文中的实验结果。此外,源码还应该尽可能具有通用性,以便在其他类似问题上进行进一步的应用和扩展。
环境说明: 开发语言:python Python版本:3.6.8 数据库:mysql 5.7 数据库工具:Navicat11 开发软件:pycharm
基于springboot高校学术交流平台源码数据库文档.zip
onnxruntime-1.16.2-cp310-cp310-win_amd64.whl
基于springboot+vue的实践性教学系统源码数据库文档.zip
基于springboot的校园二手物品交易系统源码数据库文档.zip
numpy-1.23.5-cp39-cp39-linux_armv7l.whl
bimdata_api_client-4.0.2-py3-none-any.whl
环境说明: 开发语言:PHP 框架:原生php/thinkphp5 服务器:Apache 数据库:mysql 5.7(一定要5.7版本) 数据库工具:Navicat 11 运行软件:小皮phpStudy
基于SpringBoot的中老年人文化活动平台源码数据库文档.zip