mark一个工具类
from urllib.request import quote
import urllib.request
import sqlite3
class FileUtil:
#根据url下载图片,如果没有设置图片地址,自动保存到D:\\download\\图片名称
def downImg(imgUrl,savePath=None):
imgName=imgUrl.split('/')[-1]
preUrl=imgUrl.replace(imgName,"")
if savePath is None:
savePath="D:\\download\\"+imgName
conn = urllib.request.urlopen(preUrl+quote(imgName))
f = open(savePath,'wb')
f.write(conn.read())
f.close()
print('Saved:'+savePath)
def saveNews(url,title=None,content=None):
if title is None:
title=""
if content is None:
content=""
conn = sqlite3.connect('news.db')
cursor = conn.cursor()
# 执行一条SQL语句,创建user表:
cursor.execute('create table IF NOT EXISTS news (id INTEGER PRIMARY KEY, url varchar(100),title vachar(100),content text)')
cursor.execute('select * from news where url=\''+url+'\'')
values=cursor.fetchall()
if len(values) > 0:#链接以前就存在
print('链接已经存在:'+url)
else:
cursor.execute('insert into news (url, title,content) values (\''+url+'\', \''+title+'\', \''+content+'\')')
print("save success."+url)
# 关闭Cursor:
cursor.close()
# 提交事务:
conn.commit()
# 关闭Connection:
conn.close()