本文目录一览:
- 1、在做网页,在my eclipse 中出现java.sql.SQLException: No value specified for parameter 1要怎么处理呢
- 2、如何使用webcollector爬取搜索引擎
- 3、python3 怎么爬取新闻网站
- 4、现在我想这个链接跳转到一个action方法,那么AAA应该怎么写呢?
在做网页,在my eclipse 中出现java.sql.SQLException: No value specified for parameter 1要怎么处理呢
报错为:SQL第一个条件参数没有值传入。
说明参数传递的有问题或者没传递,就会报这个错误。
举例:
String sql = “select * from users where id=? and passwd=?”;
rs = dealDateBase,getRS(sql, user,getUsername(),user,getUserPas());
备注:传递的参数个数必须与赋值的个数类型一致才可以,否则就会报错的。
拓展资料
第一步:新建web工程后,把mysql的连接驱动程序放在lib目录里。
第二步:编写数据库连接程序:import java,sql,Connection;
import java,sql,DriverManager;
public class DbConnection {
@SuppressWarnings(“finally”)
public Connection getConnection()
{
String driver =”com,mysql,jdbc,Driver”;
String url=”jdbc:mysql://localhost:3306/newssystem”;
String user=”root”;
String password=”0211″;
Connection conn=null;
//加载驱动程序以连接数据库
try {
Class,forName( driver );
conn = DriverManager,getConnection(
url, user, password );
}
catch ( ClassNotFoundException cnfex ) {
System,err,println(“数据库连接异常!!”+cnfex,getMessage());
}finally
{
return conn;
}
}
}
第三步:编写数据库操作dao类,就是对数据的增删查改。再给你举一个例子吧,这是之前做的一个小项目里,直接复制过来,你参考参考。
public class NewsDao {
Connection con;
// 添加数据
public void insertNews(News news) {
String sql = “insert into news values(0,?,?,?,now(),?,?)”;
try {
DbConnection db = new DbConnection();
con = db,getConnection();
PreparedStatement ps = con,prepareStatement(sql);
ps,setString(1, news,getTitle());
ps,setString(2, news,getContent());
ps,setString(3, news,getAuthor());
//ps,setString(4, news,getDate());
ps,setString(4, news,getSort());
ps,setString(5, news,getImage());
ps,executeUpdate();
} catch (Exception e) {
System,err,println(“数据库有误:” + e,getMessage());
} finally {
try {
if (con != null)
con,close();
} catch (Exception e2) {
System,err,println(“数据库关闭有误:” + e2,getMessage());
}
}
}
}
第四步:在相应的操作类中调用dao类;
这是按照平时的项目实施来的,如果你只是想测试连接数据库,可以这几部综合在一起。不过最后还是按照严格的分层来吧,养成一个好习惯!
如何使用webcollector爬取搜索引擎
使用webcollector爬取搜索引擎,按照关键字搜索的结果页面,解析规则可能会随百度搜索的改版而失效。
代码如下:
[java] view plain copy
package com.wjd.baidukey.crawler;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import cn.edu.hfut.dmic.contentextractor.ContentExtractor;
import cn.edu.hfut.dmic.webcollector.model.CrawlDatum;
import cn.edu.hfut.dmic.webcollector.model.CrawlDatums;
import cn.edu.hfut.dmic.webcollector.model.Page;
import cn.edu.hfut.dmic.webcollector.plugin.ram.RamCrawler;
public class BdiduKeywordCrawler extends RamCrawler{
private Connection connection;
private PreparedStatement pstatement;
// 连接MySql数据库,用户名root,密码mahao
String url = “jdbc:mysql://localhost:3306/wjd”;
String username = “root”;
String password = “mahao”;
//保存抽取到的数据
StringBuilder result = new StringBuilder();
public BdiduKeywordCrawler(String keyword, int maxPageNum) throws Exception {
for (int pageNum = 1; pageNum = maxPageNum; pageNum++) {
String url = createUrl(keyword, pageNum);
CrawlDatum datum = new CrawlDatum(url)
.putMetaData(“keyword”, keyword)
.putMetaData(“pageNum”, pageNum + “”)
.putMetaData(“pageType”, “searchEngine”)
.putMetaData(“depth”, “1”);
addSeed(datum);
}
}
@Override
public void visit(Page page, CrawlDatums next) {
String keyword = page.getMetaData(“keyword”);
String pageType = page.getMetaData(“pageType”);
int depth = Integer.valueOf(page.getMetaData(“depth”));
if (pageType.equals(“searchEngine”)) {
int pageNum = Integer.valueOf(page.getMetaData(“pageNum”));
System.out.println(“成功抓取关键词” + keyword + “的第” + pageNum + “页搜索结果”);
// || div[class=result-op c-container xpath-log ]h3a
Elements results = page.select(“div[class=result c-container ]h3a”);
// Elements results1 = page.select(“div[class=result-op c-container xpath-log]h3a”);//,div[id=result-op c-container xpath-log]h3a
//System.out.println(results1.get(0));
//results.add(results1.get(0));
for (int rank = 0; rank results.size(); rank++) {
Element result = results.get(rank);
/*
* 我们希望继续爬取每条搜索结果指向的网页,这里统称为外链。
* 我们希望在访问外链时仍然能够知道外链处于搜索引擎的第几页、第几条,
* 所以将页号和排序信息放入后续的CrawlDatum中,为了能够区分外链和
* 搜索引擎结果页面,我们将其pageType设置为outlink,这里的值完全由 用户定义,可以设置一个任意的值
* 在经典爬虫中,每个网页都有一个refer信息,表示当前网页的链接来源。
* 例如我们首先访问新浪首页,然后从新浪首页中解析出了新的新闻链接,
* 则这些网页的refer值都是新浪首页。WebCollector不直接保存refer值,
* 但我们可以通过下面的方式,将refer信息保存在metaData中,达到同样的效果。
* 经典爬虫中锚文本的存储也可以通过下面方式实现。
* 在一些需求中,希望得到当前页面在遍历树中的深度,利用metaData很容易实现
* 这个功能,在将CrawlDatum添加到next中时,将其depth设置为当前访问页面 的depth+1即可。
*/
CrawlDatum datum = new CrawlDatum(result.attr(“abs:href”))
.putMetaData(“keyword”, keyword)
.putMetaData(“pageNum”, pageNum + “”)
.putMetaData(“rank”, rank + “”)
.putMetaData(“pageType”, “outlink”)
.putMetaData(“depth”, (depth + 1) + “”)
.putMetaData(“refer”, page.getUrl());
next.add(datum);
}
} else if (pageType.equals(“outlink”)) {
/*int pageNum = Integer.valueOf(page.getMetaData(“pageNum”));
int rank = Integer.valueOf(page.getMetaData(“rank”));
String refer = page.getMetaData(“refer”);*/
try {
String content = ContentExtractor.getContentByUrl(page.getUrl());
/*String line = String.format(
“第%s页第%s个结果:标题:%s(%s字节)\tdepth=%s\trefer=%s”, pageNum,
rank + 1, page.getDoc().title(), content,
depth, refer);*/
String line = String.format(“标题:%s\n来源:%s\n正文:%s”, page.getDoc().title(),page.getUrl(),content);
HashMapString, String data = new HashMapString,String();
Date currentDate = new java.util.Date();
SimpleDateFormat myFmt = new SimpleDateFormat(“yyyy年MM月dd日 HH:mm:ss”);
TimeZone timeZoneChina = TimeZone.getTimeZone(“Asia/Shanghai”);// 获取中国的时区
myFmt.setTimeZone(timeZoneChina);// 设置系统时区
String grabTime = myFmt.format(currentDate);// new Date()为获取当前系统时间
data.put(“title”, page.getDoc().title());
data.put(“from”, page.getUrl());
data.put(“content”, content);
data.put(“grabTime”, grabTime);
//String line = String.format(“标题:%s\n”, page.getDoc().title());
//持久化到word文档中
//是否为线程安全???
//synchronized(this) {
String destFile = “D:\\”+”Result”+keyword+”.doc”;
result.append(line);
//将result写到doc文件中
write2File(destFile,result.toString());
//添加到数据库中
addResultData(data);
//}
System.out.println(line);
} catch (Exception e) {
//e.printStackTrace();
System.out.println(“链接”+page.getUrl()+”失效”);
}
}
}
//将数据保存到mysql数据库中
private void addResultData(HashMapString, String data) {
String title = data.get(“title”);
String source_url = data.get(“from”);
String content = data.get(“content”).replaceAll(“\\?{2,}”, “”);//去掉字符串中出现的多个连续问号。
//抓取时间
String grabTime = data.get(“grabTime”);
/*SimpleDateFormat format = new SimpleDateFormat(“yyyy年MM月dd日 HH:mm:ss”);
Date date = null;
try {
date = format.parse(grabTime);
} catch (Exception e) {
e.printStackTrace();
}*/
//System.out.println(“抓取时间”+grabTime);
try {
connection = DriverManager.getConnection(url, username, password);
String sql = “INSERT INTO wjd_keyword_search_table(TITLE,GRAP_TIME,CONTENT,SOURCE_URL) VALUES(?,?,?,?)”;
String checkSql = “select 1 from wjd_keyword_search_table where TITLE='” + title + “‘”;
Statement statement = connection.prepareStatement(checkSql);
ResultSet result = statement.executeQuery(checkSql);
if (!result.next()) {
// 如果数据库中不存在该记录,则添加到数据库中
pstatement = connection.prepareStatement(sql);
pstatement.setString(1, title);
//pstatement.setString(2, date);
pstatement.setString(2,grabTime);
pstatement.setString(3, content);
pstatement.setString(4, source_url);
pstatement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 将数据持久化到本地doc文件中
* @param destFile
* @param line
*/
private void write2File(String destFile, String line) {
try {
//doc content
ByteArrayInputStream bais = new ByteArrayInputStream(line.getBytes());
POIFSFileSystem fs = new POIFSFileSystem();
DirectoryEntry directory = fs.getRoot();
directory.createDocument(“WordDocument”, bais);
FileOutputStream ostream = new FileOutputStream(destFile);
fs.writeFilesystem(ostream);
bais.close();
ostream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
String[] keywordsList = {“网络爬虫”,”搜索引擎”};
int pageToal =5;
for (String keyword : keywordsList) {
BdiduKeywordCrawler crawler = new BdiduKeywordCrawler(keyword, pageToal);
crawler.start();
}
}
/**
* 根据关键词和页号拼接百度搜索对应的URL
*/
public static String createUrl(String keyword, int pageNum)
throws Exception {
int first = (pageNum-1) * 10;
keyword = URLEncoder.encode(keyword, “utf-8”);
return String.format(“;pn=%s”,
keyword, first);
}
}
python3 怎么爬取新闻网站
需求:
从门户网站爬取新闻,将新闻标题,作者,时间,内容保存到本地txt中。
用到的python模块:
import re # 正则表达式
import bs4 # Beautiful Soup 4 解析模块
import urllib2 # 网络访问模块
import News #自己定义的新闻结构
import codecs #解决编码问题的关键 ,使用codecs.open打开文件
import sys #1解决不同页面编码问题
其中bs4需要自己装一下,安装方法可以参考:Windows命令行下pip安装python whl包
程序:
#coding=utf-8
import re # 正则表达式
import bs4 # Beautiful Soup 4 解析模块
import urllib2 # 网络访问模块
import News #自己定义的新闻结构
import codecs #解决编码问题的关键 ,使用codecs.open打开文件
import sys #1解决不同页面编码问题
reload(sys) # 2
sys.setdefaultencoding(‘utf-8’) # 3
# 从首页获取所有链接
def GetAllUrl(home):
html = urllib2.urlopen(home).read().decode(‘utf8’)
soup = bs4.BeautifulSoup(html, ‘html.parser’)
pattern = ‘http://\w+\.baijia\.baidu\.com/article/\w+’
links = soup.find_all(‘a’, href=re.compile(pattern))
for link in links:
url_set.add(link[‘href’])
def GetNews(url):
global NewsCount,MaxNewsCount #全局记录新闻数量
while len(url_set) != 0:
try:
# 获取链接
url = url_set.pop()
url_old.add(url)
# 获取代码
html = urllib2.urlopen(url).read().decode(‘utf8’)
# 解析
soup = bs4.BeautifulSoup(html, ‘html.parser’)
pattern = ‘http://\w+\.baijia\.baidu\.com/article/\w+’ # 链接匹配规则
links = soup.find_all(‘a’, href=re.compile(pattern))
# 获取URL
for link in links:
if link[‘href’] not in url_old:
url_set.add(link[‘href’])
# 获取信息
article = News.News()
article.url = url # URL信息
page = soup.find(‘div’, {‘id’: ‘page’})
article.title = page.find(‘h1’).get_text() # 标题信息
info = page.find(‘div’, {‘class’: ‘article-info’})
article.author = info.find(‘a’, {‘class’: ‘name’}).get_text() # 作者信息
article.date = info.find(‘span’, {‘class’: ‘time’}).get_text() # 日期信息
article.about = page.find(‘blockquote’).get_text()
pnode = page.find(‘div’, {‘class’: ‘article-detail’}).find_all(‘p’)
article.content = ”
for node in pnode: # 获取文章段落
article.content += node.get_text() + ‘\n’ # 追加段落信息
SaveNews(article)
print NewsCount
break
except Exception as e:
print(e)
continue
else:
print(article.title)
NewsCount+=1
finally:
# 判断数据是否收集完成
if NewsCount == MaxNewsCount:
break
def SaveNews(Object):
file.write(“【”+Object.title+”】”+”\t”)
file.write(Object.author+”\t”+Object.date+”\n”)
file.write(Object.content+”\n”+”\n”)
url_set = set() # url集合
url_old = set() # 爬过的url集合
NewsCount = 0
MaxNewsCount=3
home = ” # 起始位置
GetAllUrl(home)
file=codecs.open(“D:\\test.txt”,”a+”) #文件操作
for url in url_set:
GetNews(url)
# 判断数据是否收集完成
if NewsCount == MaxNewsCount:
break
file.close()
新闻文章结构
#coding: utf-8
# 文章类定义
class News(object):
def __init__(self):
self.url = None
self.title = None
self.author = None
self.date = None
self.about = None
self.content = None
对爬取的文章数量就行统计。
现在我想这个链接跳转到一个action方法,那么AAA应该怎么写呢?
tda href=”%=request.getContextPath()%/news.do?method=edit”编辑新闻/a/td
试试楼主,不行把strtus-config贴出来我看看
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/290924.html